X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning%2Fln%2Fchannelmanager.rs;h=b1dedd51c31ab4abdcddd058dbe9191d0c8865fe;hb=0ac4dbdb8352c898100b34f0ef8ed9cebfea7786;hp=afdcaa916cfba81ef6ad7c579385dcd8b6ecd659;hpb=a82e075188fc15a103234832686915c196bfe240;p=ldk-c-bindings diff --git a/lightning-c-bindings/src/lightning/ln/channelmanager.rs b/lightning-c-bindings/src/lightning/ln/channelmanager.rs index afdcaa9..b1dedd5 100644 --- a/lightning-c-bindings/src/lightning/ln/channelmanager.rs +++ b/lightning-c-bindings/src/lightning/ln/channelmanager.rs @@ -8,60 +8,962 @@ //! The top-level channel management and payment tracking stuff lives here. //! -//! The ChannelManager is the main chunk of logic implementing the lightning protocol and is +//! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those //! upon reconnect to the relevant peer(s). //! -//! It does not manage routing logic (see routing::router::get_route for that) nor does it manage constructing +//! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing //! on-chain transactions (it only monitors the chain to watch for any force-closes that might //! imply it needs to fail HTLCs/payments/channels it manages). -//! -use std::str::FromStr; -use std::ffi::c_void; +use alloc::str::FromStr; +use alloc::string::String; +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}; + +/// Information about where a received HTLC('s onion) has indicated the HTLC should go. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum PendingHTLCRouting { + /// An HTLC which should be forwarded on to another node. + Forward { + /// The onion which should be included in the forwarded HTLC, telling the next hop what to + /// do with the HTLC. + onion_packet: crate::lightning::ln::msgs::OnionPacket, + /// The short channel ID of the channel which we were instructed to forward this HTLC to. + /// + /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning + /// to the receiving node, such as one returned from + /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`]. + short_channel_id: u64, + /// Set if this HTLC is being forwarded within a blinded path. + /// + /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None + blinded: crate::lightning::ln::channelmanager::BlindedForward, + }, + /// The onion indicates that this is a payment for an invoice (supposedly) generated by us. + /// + /// Note that at this point, we have not checked that the invoice being paid was actually + /// generated by us, but rather it's claiming to pay an invoice of ours. + Receive { + /// Information about the amount the sender intended to pay and (potential) proof that this + /// is a payment for an invoice we generated. This proof of payment is is also used for + /// linking MPP parts of a larger payment. + payment_data: crate::lightning::ln::msgs::FinalOnionHopData, + /// Additional data which we (allegedly) instructed the sender to include in the onion. + /// + /// For HTLCs received by LDK, this will ultimately be exposed in + /// [`Event::PaymentClaimable::onion_fields`] as + /// [`RecipientOnionFields::payment_metadata`]. + payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, + /// CLTV expiry of the received HTLC. + /// + /// Used to track when we should expire pending HTLCs that go unclaimed. + incoming_cltv_expiry: u32, + /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will + /// provide the onion shared secret used to decrypt the next level of forwarding + /// instructions. + /// + /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None + phantom_shared_secret: crate::c_types::ThirtyTwoBytes, + /// Custom TLVs which were set by the sender. + /// + /// For HTLCs received by LDK, this will ultimately be exposed in + /// [`Event::PaymentClaimable::onion_fields`] as + /// [`RecipientOnionFields::custom_tlvs`]. + custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ, + /// Set if this HTLC is the final hop in a multi-hop blinded path. + requires_blinded_error: bool, + }, + /// The onion indicates that this is for payment to us but which contains the preimage for + /// claiming included, and is unrelated to any invoice we'd previously generated (aka a + /// \"keysend\" or \"spontaneous\" payment). + ReceiveKeysend { + /// Information about the amount the sender intended to pay and possibly a token to + /// associate MPP parts of a larger payment. + /// + /// This will only be filled in if receiving MPP keysend payments is enabled, and it being + /// present will cause deserialization to fail on versions of LDK prior to 0.0.116. + /// + /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None + payment_data: crate::lightning::ln::msgs::FinalOnionHopData, + /// Preimage for this onion payment. This preimage is provided by the sender and will be + /// used to settle the spontaneous payment. + payment_preimage: crate::c_types::ThirtyTwoBytes, + /// Additional data which we (allegedly) instructed the sender to include in the onion. + /// + /// For HTLCs received by LDK, this will ultimately bubble back up as + /// [`RecipientOnionFields::payment_metadata`]. + payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, + /// CLTV expiry of the received HTLC. + /// + /// Used to track when we should expire pending HTLCs that go unclaimed. + incoming_cltv_expiry: u32, + /// Custom TLVs which were set by the sender. + /// + /// For HTLCs received by LDK, these will ultimately bubble back up as + /// [`RecipientOnionFields::custom_tlvs`]. + custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ, + }, +} +use lightning::ln::channelmanager::PendingHTLCRouting as PendingHTLCRoutingImport; +pub(crate) type nativePendingHTLCRouting = PendingHTLCRoutingImport; + +impl PendingHTLCRouting { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativePendingHTLCRouting { + match self { + PendingHTLCRouting::Forward {ref onion_packet, ref short_channel_id, ref blinded, } => { + let mut onion_packet_nonref = Clone::clone(onion_packet); + let mut short_channel_id_nonref = Clone::clone(short_channel_id); + let mut blinded_nonref = Clone::clone(blinded); + let mut local_blinded_nonref = if blinded_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(blinded_nonref.take_inner()) } }) }; + nativePendingHTLCRouting::Forward { + onion_packet: *unsafe { Box::from_raw(onion_packet_nonref.take_inner()) }, + short_channel_id: short_channel_id_nonref, + blinded: local_blinded_nonref, + } + }, + PendingHTLCRouting::Receive {ref payment_data, ref payment_metadata, ref incoming_cltv_expiry, ref phantom_shared_secret, ref custom_tlvs, ref requires_blinded_error, } => { + let mut payment_data_nonref = Clone::clone(payment_data); + let mut payment_metadata_nonref = Clone::clone(payment_metadata); + let mut local_payment_metadata_nonref = { /*payment_metadata_nonref*/ let payment_metadata_nonref_opt = payment_metadata_nonref; if payment_metadata_nonref_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in { payment_metadata_nonref_opt.take() }.into_rust().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0 }})} }; + let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry); + let mut phantom_shared_secret_nonref = Clone::clone(phantom_shared_secret); + let mut local_phantom_shared_secret_nonref = if phantom_shared_secret_nonref.data == [0; 32] { None } else { Some( { phantom_shared_secret_nonref.data }) }; + let mut custom_tlvs_nonref = Clone::clone(custom_tlvs); + let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.into_rust().drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.into_rust().drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1); local_custom_tlvs_nonref_0 }); }; + let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error); + nativePendingHTLCRouting::Receive { + payment_data: *unsafe { Box::from_raw(payment_data_nonref.take_inner()) }, + payment_metadata: local_payment_metadata_nonref, + incoming_cltv_expiry: incoming_cltv_expiry_nonref, + phantom_shared_secret: local_phantom_shared_secret_nonref, + custom_tlvs: local_custom_tlvs_nonref, + requires_blinded_error: requires_blinded_error_nonref, + } + }, + PendingHTLCRouting::ReceiveKeysend {ref payment_data, ref payment_preimage, ref payment_metadata, ref incoming_cltv_expiry, ref custom_tlvs, } => { + let mut payment_data_nonref = Clone::clone(payment_data); + let mut local_payment_data_nonref = if payment_data_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payment_data_nonref.take_inner()) } }) }; + let mut payment_preimage_nonref = Clone::clone(payment_preimage); + let mut payment_metadata_nonref = Clone::clone(payment_metadata); + let mut local_payment_metadata_nonref = { /*payment_metadata_nonref*/ let payment_metadata_nonref_opt = payment_metadata_nonref; if payment_metadata_nonref_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in { payment_metadata_nonref_opt.take() }.into_rust().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0 }})} }; + let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry); + let mut custom_tlvs_nonref = Clone::clone(custom_tlvs); + let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.into_rust().drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.into_rust().drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1); local_custom_tlvs_nonref_0 }); }; + nativePendingHTLCRouting::ReceiveKeysend { + payment_data: local_payment_data_nonref, + payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage_nonref.data), + payment_metadata: local_payment_metadata_nonref, + incoming_cltv_expiry: incoming_cltv_expiry_nonref, + custom_tlvs: local_custom_tlvs_nonref, + } + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativePendingHTLCRouting { + match self { + PendingHTLCRouting::Forward {mut onion_packet, mut short_channel_id, mut blinded, } => { + let mut local_blinded = if blinded.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(blinded.take_inner()) } }) }; + nativePendingHTLCRouting::Forward { + onion_packet: *unsafe { Box::from_raw(onion_packet.take_inner()) }, + short_channel_id: short_channel_id, + blinded: local_blinded, + } + }, + PendingHTLCRouting::Receive {mut payment_data, mut payment_metadata, mut incoming_cltv_expiry, mut phantom_shared_secret, mut custom_tlvs, mut requires_blinded_error, } => { + let mut local_payment_metadata = { /*payment_metadata*/ let payment_metadata_opt = payment_metadata; if payment_metadata_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_0 = Vec::new(); for mut item in { payment_metadata_opt.take() }.into_rust().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0 }})} }; + let mut local_phantom_shared_secret = if phantom_shared_secret.data == [0; 32] { None } else { Some( { phantom_shared_secret.data }) }; + let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.into_rust().drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.into_rust().drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1); local_custom_tlvs_0 }); }; + nativePendingHTLCRouting::Receive { + payment_data: *unsafe { Box::from_raw(payment_data.take_inner()) }, + payment_metadata: local_payment_metadata, + incoming_cltv_expiry: incoming_cltv_expiry, + phantom_shared_secret: local_phantom_shared_secret, + custom_tlvs: local_custom_tlvs, + requires_blinded_error: requires_blinded_error, + } + }, + PendingHTLCRouting::ReceiveKeysend {mut payment_data, mut payment_preimage, mut payment_metadata, mut incoming_cltv_expiry, mut custom_tlvs, } => { + let mut local_payment_data = if payment_data.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payment_data.take_inner()) } }) }; + let mut local_payment_metadata = { /*payment_metadata*/ let payment_metadata_opt = payment_metadata; if payment_metadata_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_0 = Vec::new(); for mut item in { payment_metadata_opt.take() }.into_rust().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0 }})} }; + let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.into_rust().drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.into_rust().drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1); local_custom_tlvs_0 }); }; + nativePendingHTLCRouting::ReceiveKeysend { + payment_data: local_payment_data, + payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage.data), + payment_metadata: local_payment_metadata, + incoming_cltv_expiry: incoming_cltv_expiry, + custom_tlvs: local_custom_tlvs, + } + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &PendingHTLCRoutingImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativePendingHTLCRouting) }; + match native { + nativePendingHTLCRouting::Forward {ref onion_packet, ref short_channel_id, ref blinded, } => { + let mut onion_packet_nonref = Clone::clone(onion_packet); + let mut short_channel_id_nonref = Clone::clone(short_channel_id); + let mut blinded_nonref = Clone::clone(blinded); + let mut local_blinded_nonref = crate::lightning::ln::channelmanager::BlindedForward { inner: if blinded_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((blinded_nonref.unwrap())) } }, is_owned: true }; + PendingHTLCRouting::Forward { + onion_packet: crate::lightning::ln::msgs::OnionPacket { inner: ObjOps::heap_alloc(onion_packet_nonref), is_owned: true }, + short_channel_id: short_channel_id_nonref, + blinded: local_blinded_nonref, + } + }, + nativePendingHTLCRouting::Receive {ref payment_data, ref payment_metadata, ref incoming_cltv_expiry, ref phantom_shared_secret, ref custom_tlvs, ref requires_blinded_error, } => { + let mut payment_data_nonref = Clone::clone(payment_data); + let mut payment_metadata_nonref = Clone::clone(payment_metadata); + let mut local_payment_metadata_nonref = if payment_metadata_nonref.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in payment_metadata_nonref.unwrap().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0.into() }) }; + let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry); + let mut phantom_shared_secret_nonref = Clone::clone(phantom_shared_secret); + let mut local_phantom_shared_secret_nonref = if phantom_shared_secret_nonref.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else { { crate::c_types::ThirtyTwoBytes { data: (phantom_shared_secret_nonref.unwrap()) } } }; + let mut custom_tlvs_nonref = Clone::clone(custom_tlvs); + let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item; let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1.into()).into(); local_custom_tlvs_nonref_0 }); }; + let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error); + PendingHTLCRouting::Receive { + payment_data: crate::lightning::ln::msgs::FinalOnionHopData { inner: ObjOps::heap_alloc(payment_data_nonref), is_owned: true }, + payment_metadata: local_payment_metadata_nonref, + incoming_cltv_expiry: incoming_cltv_expiry_nonref, + phantom_shared_secret: local_phantom_shared_secret_nonref, + custom_tlvs: local_custom_tlvs_nonref.into(), + requires_blinded_error: requires_blinded_error_nonref, + } + }, + nativePendingHTLCRouting::ReceiveKeysend {ref payment_data, ref payment_preimage, ref payment_metadata, ref incoming_cltv_expiry, ref custom_tlvs, } => { + let mut payment_data_nonref = Clone::clone(payment_data); + let mut local_payment_data_nonref = crate::lightning::ln::msgs::FinalOnionHopData { inner: if payment_data_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((payment_data_nonref.unwrap())) } }, is_owned: true }; + let mut payment_preimage_nonref = Clone::clone(payment_preimage); + let mut payment_metadata_nonref = Clone::clone(payment_metadata); + let mut local_payment_metadata_nonref = if payment_metadata_nonref.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in payment_metadata_nonref.unwrap().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0.into() }) }; + let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry); + let mut custom_tlvs_nonref = Clone::clone(custom_tlvs); + let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item; let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1.into()).into(); local_custom_tlvs_nonref_0 }); }; + PendingHTLCRouting::ReceiveKeysend { + payment_data: local_payment_data_nonref, + payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage_nonref.0 }, + payment_metadata: local_payment_metadata_nonref, + incoming_cltv_expiry: incoming_cltv_expiry_nonref, + custom_tlvs: local_custom_tlvs_nonref.into(), + } + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativePendingHTLCRouting) -> Self { + match native { + nativePendingHTLCRouting::Forward {mut onion_packet, mut short_channel_id, mut blinded, } => { + let mut local_blinded = crate::lightning::ln::channelmanager::BlindedForward { inner: if blinded.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((blinded.unwrap())) } }, is_owned: true }; + PendingHTLCRouting::Forward { + onion_packet: crate::lightning::ln::msgs::OnionPacket { inner: ObjOps::heap_alloc(onion_packet), is_owned: true }, + short_channel_id: short_channel_id, + blinded: local_blinded, + } + }, + nativePendingHTLCRouting::Receive {mut payment_data, mut payment_metadata, mut incoming_cltv_expiry, mut phantom_shared_secret, mut custom_tlvs, mut requires_blinded_error, } => { + let mut local_payment_metadata = if payment_metadata.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_0 = Vec::new(); for mut item in payment_metadata.unwrap().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0.into() }) }; + let mut local_phantom_shared_secret = if phantom_shared_secret.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else { { crate::c_types::ThirtyTwoBytes { data: (phantom_shared_secret.unwrap()) } } }; + let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item; let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1.into()).into(); local_custom_tlvs_0 }); }; + PendingHTLCRouting::Receive { + payment_data: crate::lightning::ln::msgs::FinalOnionHopData { inner: ObjOps::heap_alloc(payment_data), is_owned: true }, + payment_metadata: local_payment_metadata, + incoming_cltv_expiry: incoming_cltv_expiry, + phantom_shared_secret: local_phantom_shared_secret, + custom_tlvs: local_custom_tlvs.into(), + requires_blinded_error: requires_blinded_error, + } + }, + nativePendingHTLCRouting::ReceiveKeysend {mut payment_data, mut payment_preimage, mut payment_metadata, mut incoming_cltv_expiry, mut custom_tlvs, } => { + let mut local_payment_data = crate::lightning::ln::msgs::FinalOnionHopData { inner: if payment_data.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((payment_data.unwrap())) } }, is_owned: true }; + let mut local_payment_metadata = if payment_metadata.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_0 = Vec::new(); for mut item in payment_metadata.unwrap().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0.into() }) }; + let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item; let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1.into()).into(); local_custom_tlvs_0 }); }; + PendingHTLCRouting::ReceiveKeysend { + payment_data: local_payment_data, + payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage.0 }, + payment_metadata: local_payment_metadata, + incoming_cltv_expiry: incoming_cltv_expiry, + custom_tlvs: local_custom_tlvs.into(), + } + }, + } + } +} +/// Frees any resources used by the PendingHTLCRouting +#[no_mangle] +pub extern "C" fn PendingHTLCRouting_free(this_ptr: PendingHTLCRouting) { } +/// Creates a copy of the PendingHTLCRouting +#[no_mangle] +pub extern "C" fn PendingHTLCRouting_clone(orig: &PendingHTLCRouting) -> PendingHTLCRouting { + orig.clone() +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PendingHTLCRouting_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const PendingHTLCRouting)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PendingHTLCRouting_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut PendingHTLCRouting) }; +} +#[no_mangle] +/// Utility method to constructs a new Forward-variant PendingHTLCRouting +pub extern "C" fn PendingHTLCRouting_forward(onion_packet: crate::lightning::ln::msgs::OnionPacket, short_channel_id: u64, blinded: crate::lightning::ln::channelmanager::BlindedForward) -> PendingHTLCRouting { + PendingHTLCRouting::Forward { + onion_packet, + short_channel_id, + blinded, + } +} +#[no_mangle] +/// Utility method to constructs a new Receive-variant PendingHTLCRouting +pub extern "C" fn PendingHTLCRouting_receive(payment_data: crate::lightning::ln::msgs::FinalOnionHopData, payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, incoming_cltv_expiry: u32, phantom_shared_secret: crate::c_types::ThirtyTwoBytes, custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ, requires_blinded_error: bool) -> PendingHTLCRouting { + PendingHTLCRouting::Receive { + payment_data, + payment_metadata, + incoming_cltv_expiry, + phantom_shared_secret, + custom_tlvs, + requires_blinded_error, + } +} +#[no_mangle] +/// Utility method to constructs a new ReceiveKeysend-variant PendingHTLCRouting +pub extern "C" fn PendingHTLCRouting_receive_keysend(payment_data: crate::lightning::ln::msgs::FinalOnionHopData, payment_preimage: crate::c_types::ThirtyTwoBytes, payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, incoming_cltv_expiry: u32, custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ) -> PendingHTLCRouting { + PendingHTLCRouting::ReceiveKeysend { + payment_data, + payment_preimage, + payment_metadata, + incoming_cltv_expiry, + custom_tlvs, + } +} + +use lightning::ln::channelmanager::BlindedForward as nativeBlindedForwardImport; +pub(crate) type nativeBlindedForward = nativeBlindedForwardImport; + +/// Information used to forward or fail this HTLC that is being forwarded within a blinded path. +#[must_use] +#[repr(C)] +pub struct BlindedForward { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeBlindedForward, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for BlindedForward { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeBlindedForward>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the BlindedForward, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn BlindedForward_free(this_obj: BlindedForward) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedForward_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBlindedForward) }; +} +#[allow(unused)] +impl BlindedForward { + pub(crate) fn get_native_ref(&self) -> &'static nativeBlindedForward { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBlindedForward { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeBlindedForward { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +/// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound +/// onion payload if we're the introduction node. Useful for calculating the next hop's +/// [`msgs::UpdateAddHTLC::blinding_point`]. +#[no_mangle] +pub extern "C" fn BlindedForward_get_inbound_blinding_point(this_ptr: &BlindedForward) -> crate::c_types::PublicKey { + let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_blinding_point; + crate::c_types::PublicKey::from_rust(&inner_val) +} +/// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound +/// onion payload if we're the introduction node. Useful for calculating the next hop's +/// [`msgs::UpdateAddHTLC::blinding_point`]. +#[no_mangle] +pub extern "C" fn BlindedForward_set_inbound_blinding_point(this_ptr: &mut BlindedForward, mut val: crate::c_types::PublicKey) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_blinding_point = val.into_rust(); +} +/// If needed, this determines how this HTLC should be failed backwards, based on whether we are +/// the introduction node. +#[no_mangle] +pub extern "C" fn BlindedForward_get_failure(this_ptr: &BlindedForward) -> crate::lightning::ln::channelmanager::BlindedFailure { + let mut inner_val = &mut this_ptr.get_native_mut_ref().failure; + crate::lightning::ln::channelmanager::BlindedFailure::from_native(inner_val) +} +/// If needed, this determines how this HTLC should be failed backwards, based on whether we are +/// the introduction node. +#[no_mangle] +pub extern "C" fn BlindedForward_set_failure(this_ptr: &mut BlindedForward, mut val: crate::lightning::ln::channelmanager::BlindedFailure) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure = val.into_native(); +} +/// Constructs a new BlindedForward given each field +#[must_use] +#[no_mangle] +pub extern "C" fn BlindedForward_new(mut inbound_blinding_point_arg: crate::c_types::PublicKey, mut failure_arg: crate::lightning::ln::channelmanager::BlindedFailure) -> BlindedForward { + BlindedForward { inner: ObjOps::heap_alloc(nativeBlindedForward { + inbound_blinding_point: inbound_blinding_point_arg.into_rust(), + failure: failure_arg.into_native(), + }), is_owned: true } +} +impl Clone for BlindedForward { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeBlindedForward>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedForward_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeBlindedForward)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the BlindedForward +pub extern "C" fn BlindedForward_clone(orig: &BlindedForward) -> BlindedForward { + orig.clone() +} +/// Get a string which allows debug introspection of a BlindedForward object +pub extern "C" fn BlindedForward_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::BlindedForward }).into()} +/// Generates a non-cryptographic 64-bit hash of the BlindedForward. +#[no_mangle] +pub extern "C" fn BlindedForward_hash(o: &BlindedForward) -> u64 { + if o.inner.is_null() { return 0; } + // 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(); + core::hash::Hash::hash(o.get_native_ref(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two BlindedForwards contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn BlindedForward_eq(a: &BlindedForward, b: &BlindedForward) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} + +use lightning::ln::channelmanager::PendingHTLCInfo as nativePendingHTLCInfoImport; +pub(crate) type nativePendingHTLCInfo = nativePendingHTLCInfoImport; +/// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it +/// should go next. +#[must_use] +#[repr(C)] +pub struct PendingHTLCInfo { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativePendingHTLCInfo, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for PendingHTLCInfo { + fn drop(&mut self) { + if self.is_owned && !<*mut nativePendingHTLCInfo>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the PendingHTLCInfo, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_free(this_obj: PendingHTLCInfo) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PendingHTLCInfo_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativePendingHTLCInfo) }; +} +#[allow(unused)] +impl PendingHTLCInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativePendingHTLCInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePendingHTLCInfo { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativePendingHTLCInfo { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +/// Further routing details based on whether the HTLC is being forwarded or received. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_routing(this_ptr: &PendingHTLCInfo) -> crate::lightning::ln::channelmanager::PendingHTLCRouting { + let mut inner_val = &mut this_ptr.get_native_mut_ref().routing; + crate::lightning::ln::channelmanager::PendingHTLCRouting::from_native(inner_val) +} +/// Further routing details based on whether the HTLC is being forwarded or received. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_routing(this_ptr: &mut PendingHTLCInfo, mut val: crate::lightning::ln::channelmanager::PendingHTLCRouting) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.routing = val.into_native(); +} +/// The onion shared secret we build with the sender used to decrypt the onion. +/// +/// This is later used to encrypt failure packets in the event that the HTLC is failed. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_incoming_shared_secret(this_ptr: &PendingHTLCInfo) -> *const [u8; 32] { + let mut inner_val = &mut this_ptr.get_native_mut_ref().incoming_shared_secret; + inner_val +} +/// The onion shared secret we build with the sender used to decrypt the onion. +/// +/// This is later used to encrypt failure packets in the event that the HTLC is failed. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_incoming_shared_secret(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::ThirtyTwoBytes) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.incoming_shared_secret = val.data; +} +/// Hash of the payment preimage, to lock the payment until the receiver releases the preimage. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_payment_hash(this_ptr: &PendingHTLCInfo) -> *const [u8; 32] { + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_hash; + &inner_val.0 +} +/// Hash of the payment preimage, to lock the payment until the receiver releases the preimage. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_payment_hash(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::ThirtyTwoBytes) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_hash = ::lightning::ln::PaymentHash(val.data); +} +/// Amount received in the incoming HTLC. +/// +/// This field was added in LDK 0.0.113 and will be `None` for objects written by prior +/// versions. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_incoming_amt_msat(this_ptr: &PendingHTLCInfo) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().incoming_amt_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// Amount received in the incoming HTLC. +/// +/// This field was added in LDK 0.0.113 and will be `None` for objects written by prior +/// versions. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_incoming_amt_msat(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.incoming_amt_msat = local_val; +} +/// The amount the sender indicated should be forwarded on to the next hop or amount the sender +/// intended for us to receive for received payments. +/// +/// If the received amount is less than this for received payments, an intermediary hop has +/// attempted to steal some of our funds and we should fail the HTLC (the sender should retry +/// it along another path). +/// +/// Because nodes can take less than their required fees, and because senders may wish to +/// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for +/// received payments. In such cases, recipients must handle this HTLC as if it had received +/// [`Self::outgoing_amt_msat`]. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_outgoing_amt_msat(this_ptr: &PendingHTLCInfo) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().outgoing_amt_msat; + *inner_val +} +/// The amount the sender indicated should be forwarded on to the next hop or amount the sender +/// intended for us to receive for received payments. +/// +/// If the received amount is less than this for received payments, an intermediary hop has +/// attempted to steal some of our funds and we should fail the HTLC (the sender should retry +/// it along another path). +/// +/// Because nodes can take less than their required fees, and because senders may wish to +/// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for +/// received payments. In such cases, recipients must handle this HTLC as if it had received +/// [`Self::outgoing_amt_msat`]. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_outgoing_amt_msat(this_ptr: &mut PendingHTLCInfo, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outgoing_amt_msat = val; +} +/// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated +/// should have been set on the received HTLC for received payments). +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_outgoing_cltv_value(this_ptr: &PendingHTLCInfo) -> u32 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().outgoing_cltv_value; + *inner_val +} +/// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated +/// should have been set on the received HTLC for received payments). +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_outgoing_cltv_value(this_ptr: &mut PendingHTLCInfo, mut val: u32) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outgoing_cltv_value = val; +} +/// The fee taken for this HTLC in addition to the standard protocol HTLC fees. +/// +/// If this is a payment for forwarding, this is the fee we are taking before forwarding the +/// HTLC. +/// +/// If this is a received payment, this is the fee that our counterparty took. +/// +/// This is used to allow LSPs to take fees as a part of payments, without the sender having to +/// shoulder them. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_get_skimmed_fee_msat(this_ptr: &PendingHTLCInfo) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().skimmed_fee_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The fee taken for this HTLC in addition to the standard protocol HTLC fees. +/// +/// If this is a payment for forwarding, this is the fee we are taking before forwarding the +/// HTLC. +/// +/// If this is a received payment, this is the fee that our counterparty took. +/// +/// This is used to allow LSPs to take fees as a part of payments, without the sender having to +/// shoulder them. +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_set_skimmed_fee_msat(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.skimmed_fee_msat = local_val; +} +/// Constructs a new PendingHTLCInfo given each field +#[must_use] +#[no_mangle] +pub extern "C" fn PendingHTLCInfo_new(mut routing_arg: crate::lightning::ln::channelmanager::PendingHTLCRouting, mut incoming_shared_secret_arg: crate::c_types::ThirtyTwoBytes, mut payment_hash_arg: crate::c_types::ThirtyTwoBytes, mut incoming_amt_msat_arg: crate::c_types::derived::COption_u64Z, mut outgoing_amt_msat_arg: u64, mut outgoing_cltv_value_arg: u32, mut skimmed_fee_msat_arg: crate::c_types::derived::COption_u64Z) -> PendingHTLCInfo { + let mut local_incoming_amt_msat_arg = if incoming_amt_msat_arg.is_some() { Some( { incoming_amt_msat_arg.take() }) } else { None }; + let mut local_skimmed_fee_msat_arg = if skimmed_fee_msat_arg.is_some() { Some( { skimmed_fee_msat_arg.take() }) } else { None }; + PendingHTLCInfo { inner: ObjOps::heap_alloc(nativePendingHTLCInfo { + routing: routing_arg.into_native(), + incoming_shared_secret: incoming_shared_secret_arg.data, + payment_hash: ::lightning::ln::PaymentHash(payment_hash_arg.data), + incoming_amt_msat: local_incoming_amt_msat_arg, + outgoing_amt_msat: outgoing_amt_msat_arg, + outgoing_cltv_value: outgoing_cltv_value_arg, + skimmed_fee_msat: local_skimmed_fee_msat_arg, + }), is_owned: true } +} +impl Clone for PendingHTLCInfo { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativePendingHTLCInfo>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PendingHTLCInfo_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativePendingHTLCInfo)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the PendingHTLCInfo +pub extern "C" fn PendingHTLCInfo_clone(orig: &PendingHTLCInfo) -> PendingHTLCInfo { + orig.clone() +} +/// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node, +/// which determines the failure message that should be used. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum BlindedFailure { + /// This HTLC is being failed backwards by the introduction node, and thus should be failed with + /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`. + FromIntroductionNode, + /// This HTLC is being failed backwards by a blinded node within the path, and thus should be + /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`. + FromBlindedNode, +} +use lightning::ln::channelmanager::BlindedFailure as BlindedFailureImport; +pub(crate) type nativeBlindedFailure = BlindedFailureImport; + +impl BlindedFailure { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeBlindedFailure { + match self { + BlindedFailure::FromIntroductionNode => nativeBlindedFailure::FromIntroductionNode, + BlindedFailure::FromBlindedNode => nativeBlindedFailure::FromBlindedNode, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeBlindedFailure { + match self { + BlindedFailure::FromIntroductionNode => nativeBlindedFailure::FromIntroductionNode, + BlindedFailure::FromBlindedNode => nativeBlindedFailure::FromBlindedNode, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &BlindedFailureImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeBlindedFailure) }; + match native { + nativeBlindedFailure::FromIntroductionNode => BlindedFailure::FromIntroductionNode, + nativeBlindedFailure::FromBlindedNode => BlindedFailure::FromBlindedNode, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeBlindedFailure) -> Self { + match native { + nativeBlindedFailure::FromIntroductionNode => BlindedFailure::FromIntroductionNode, + nativeBlindedFailure::FromBlindedNode => BlindedFailure::FromBlindedNode, + } + } +} +/// Creates a copy of the BlindedFailure +#[no_mangle] +pub extern "C" fn BlindedFailure_clone(orig: &BlindedFailure) -> BlindedFailure { + orig.clone() +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedFailure_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const BlindedFailure)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedFailure_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut BlindedFailure) }; +} +#[no_mangle] +/// Utility method to constructs a new FromIntroductionNode-variant BlindedFailure +pub extern "C" fn BlindedFailure_from_introduction_node() -> BlindedFailure { + BlindedFailure::FromIntroductionNode} +#[no_mangle] +/// Utility method to constructs a new FromBlindedNode-variant BlindedFailure +pub extern "C" fn BlindedFailure_from_blinded_node() -> BlindedFailure { + BlindedFailure::FromBlindedNode} +/// Get a string which allows debug introspection of a BlindedFailure object +pub extern "C" fn BlindedFailure_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::BlindedFailure }).into()} +/// Generates a non-cryptographic 64-bit hash of the BlindedFailure. +#[no_mangle] +pub extern "C" fn BlindedFailure_hash(o: &BlindedFailure) -> u64 { + // 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(); + core::hash::Hash::hash(&o.to_native(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Checks if two BlindedFailures contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn BlindedFailure_eq(a: &BlindedFailure, b: &BlindedFailure) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} +/// This enum is used to specify which error data to send to peers when failing back an HTLC +/// using [`ChannelManager::fail_htlc_backwards_with_reason`]. +/// +/// For more info on failure codes, see . +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum FailureCode { + /// We had a temporary error processing the payment. Useful if no other error codes fit + /// and you want to indicate that the payer may want to retry. + TemporaryNodeFailure, + /// We have a required feature which was not in this onion. For example, you may require + /// some additional metadata that was not provided with this payment. + RequiredNodeFeatureMissing, + /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of + /// the HTLC is too close to the current block height for safe handling. + /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is + /// equivalent to calling [`ChannelManager::fail_htlc_backwards`]. + IncorrectOrUnknownPaymentDetails, + /// We failed to process the payload after the onion was decrypted. You may wish to + /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize. + /// + /// If available, the tuple data may include the type number and byte offset in the + /// decrypted byte stream where the failure occurred. + InvalidOnionPayload( + crate::c_types::derived::COption_C2Tuple_u64u16ZZ), +} +use lightning::ln::channelmanager::FailureCode as FailureCodeImport; +pub(crate) type nativeFailureCode = FailureCodeImport; + +impl FailureCode { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeFailureCode { + match self { + FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure, + FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing, + FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails, + FailureCode::InvalidOnionPayload (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = if a_nonref.is_some() { Some( { let (mut orig_a_nonref_0_0, mut orig_a_nonref_0_1) = a_nonref.take().to_rust(); let mut local_a_nonref_0 = (orig_a_nonref_0_0, orig_a_nonref_0_1); local_a_nonref_0 }) } else { None }; + nativeFailureCode::InvalidOnionPayload ( + local_a_nonref, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeFailureCode { + match self { + FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure, + FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing, + FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails, + FailureCode::InvalidOnionPayload (mut a, ) => { + let mut local_a = if a.is_some() { Some( { let (mut orig_a_0_0, mut orig_a_0_1) = a.take().to_rust(); let mut local_a_0 = (orig_a_0_0, orig_a_0_1); local_a_0 }) } else { None }; + nativeFailureCode::InvalidOnionPayload ( + local_a, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &FailureCodeImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeFailureCode) }; + match native { + nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure, + nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing, + nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails, + nativeFailureCode::InvalidOnionPayload (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = if a_nonref.is_none() { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::Some( { let (mut orig_a_nonref_0_0, mut orig_a_nonref_0_1) = (a_nonref.unwrap()); let mut local_a_nonref_0 = (orig_a_nonref_0_0, orig_a_nonref_0_1).into(); local_a_nonref_0 }) }; + FailureCode::InvalidOnionPayload ( + local_a_nonref, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeFailureCode) -> Self { + match native { + nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure, + nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing, + nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails, + nativeFailureCode::InvalidOnionPayload (mut a, ) => { + let mut local_a = if a.is_none() { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::Some( { let (mut orig_a_0_0, mut orig_a_0_1) = (a.unwrap()); let mut local_a_0 = (orig_a_0_0, orig_a_0_1).into(); local_a_0 }) }; + FailureCode::InvalidOnionPayload ( + local_a, + ) + }, + } + } +} +/// Frees any resources used by the FailureCode +#[no_mangle] +pub extern "C" fn FailureCode_free(this_ptr: FailureCode) { } +/// Creates a copy of the FailureCode +#[no_mangle] +pub extern "C" fn FailureCode_clone(orig: &FailureCode) -> FailureCode { + orig.clone() +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn FailureCode_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const FailureCode)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn FailureCode_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut FailureCode) }; +} +#[no_mangle] +/// Utility method to constructs a new TemporaryNodeFailure-variant FailureCode +pub extern "C" fn FailureCode_temporary_node_failure() -> FailureCode { + FailureCode::TemporaryNodeFailure} +#[no_mangle] +/// Utility method to constructs a new RequiredNodeFeatureMissing-variant FailureCode +pub extern "C" fn FailureCode_required_node_feature_missing() -> FailureCode { + FailureCode::RequiredNodeFeatureMissing} +#[no_mangle] +/// Utility method to constructs a new IncorrectOrUnknownPaymentDetails-variant FailureCode +pub extern "C" fn FailureCode_incorrect_or_unknown_payment_details() -> FailureCode { + FailureCode::IncorrectOrUnknownPaymentDetails} +#[no_mangle] +/// Utility method to constructs a new InvalidOnionPayload-variant FailureCode +pub extern "C" fn FailureCode_invalid_onion_payload(a: crate::c_types::derived::COption_C2Tuple_u64u16ZZ) -> FailureCode { + FailureCode::InvalidOnionPayload(a, ) +} use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport; -type nativeChannelManager = nativeChannelManagerImport; +pub(crate) type nativeChannelManager = nativeChannelManagerImport; /// Manager which keeps track of a number of channels and sends messages to the appropriate /// channel, also tracking HTLC preimages and forwarding onion packets appropriately. /// -/// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through +/// Implements [`ChannelMessageHandler`], handling the multi-channel parts and passing things through /// to individual Channels. /// -/// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for +/// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for /// all peers during write/read (though does not modify this instance, only the instance being -/// serialized). This will result in any channels which have not yet exchanged funding_created (ie -/// called funding_transaction_generated for outbound channels). -/// -/// Note that you can be a bit lazier about writing out ChannelManager than you can be with -/// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before -/// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates -/// happens out-of-band (and will prevent any other ChannelManager operations from occurring during -/// the serialization process). If the deserialized version is out-of-date compared to the -/// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the -/// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees). -/// -/// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which -/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along -/// the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call -/// block_connected() to step towards your best block) upon deserialization before using the -/// object! -/// -/// Note that ChannelManager is responsible for tracking liveness of its channels and generating -/// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid +/// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e., +/// called [`funding_transaction_generated`] for outbound channels) being closed. +/// +/// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with +/// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each +/// [`ChannelMonitorUpdate`] before returning from +/// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With +/// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other +/// `ChannelManager` operations from occurring during the serialization process). If the +/// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to +/// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds +/// will be lost (modulo on-chain transaction fees). +/// +/// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which +/// tells you the last block hash which was connected. You should get the best block tip before using the manager. +/// See [`chain::Listen`] and [`chain::Confirm`] for more details. +/// +/// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating +/// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been /// offline for a full minute. In order to track this, you must call -/// timer_tick_occurred roughly once per minute, though it doesn't have to be perfect. +/// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect. +/// +/// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and +/// inbound channels without confirmed funding transactions. This may result in nodes which we do +/// not have a channel with being unable to connect to us or open new channels with us if we have +/// many peers with unfunded channels. /// -/// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager -/// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but -/// essentially you should default to using a SimpleRefChannelManager, and use a -/// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when +/// Because it is an indication of trust, inbound channels which we've accepted as 0conf are +/// exempted from the count of unfunded channels. Similarly, outbound channels and connections are +/// never limited. Please ensure you limit the count of such channels yourself. +/// +/// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`] +/// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but +/// essentially you should default to using a [`SimpleRefChannelManager`], and use a +/// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when /// you're using lightning-net-tokio. +/// +/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected +/// [`funding_created`]: msgs::FundingCreated +/// [`funding_transaction_generated`]: Self::funding_transaction_generated +/// [`BlockHash`]: bitcoin::hash_types::BlockHash +/// [`update_channel`]: chain::Watch::update_channel +/// [`ChannelUpdate`]: msgs::ChannelUpdate +/// [`timer_tick_occurred`]: Self::timer_tick_occurred +/// [`read`]: ReadableArgs::read #[must_use] #[repr(C)] pub struct ChannelManager { @@ -80,7 +982,7 @@ pub struct ChannelManager { impl Drop for ChannelManager { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelManager>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -89,22 +991,28 @@ impl Drop for ChannelManager { pub extern "C" fn ChannelManager_free(this_obj: ChannelManager) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManager); } +pub(crate) extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelManager) }; } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelManager { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManager { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManager { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } use lightning::ln::channelmanager::ChainParameters as nativeChainParametersImport; -type nativeChainParameters = nativeChainParametersImport; +pub(crate) type nativeChainParameters = nativeChainParametersImport; /// Chain-related parameters used to construct a new `ChannelManager`. /// @@ -128,110 +1036,236 @@ pub struct ChainParameters { impl Drop for ChainParameters { fn drop(&mut self) { - if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the ChainParameters, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn ChainParameters_free(this_obj: ChainParameters) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChainParameters) }; +} +#[allow(unused)] +impl ChainParameters { + pub(crate) fn get_native_ref(&self) -> &'static nativeChainParameters { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainParameters { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +/// The network for determining the `chain_hash` in Lightning messages. +#[no_mangle] +pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network { + let mut inner_val = &mut this_ptr.get_native_mut_ref().network; + crate::bitcoin::network::Network::from_bitcoin(inner_val) +} +/// The network for determining the `chain_hash` in Lightning messages. +#[no_mangle] +pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.network = val.into_bitcoin(); +} +/// The hash and height of the latest block successfully connected. +/// +/// Used to track on-chain channel funding outputs and send payments with reliable timelocks. +#[no_mangle] +pub extern "C" fn ChainParameters_get_best_block(this_ptr: &ChainParameters) -> crate::lightning::chain::BestBlock { + let mut inner_val = &mut this_ptr.get_native_mut_ref().best_block; + crate::lightning::chain::BestBlock { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::chain::BestBlock<>) as *mut _) }, is_owned: false } +} +/// The hash and height of the latest block successfully connected. +/// +/// Used to track on-chain channel funding outputs and send payments with reliable timelocks. +#[no_mangle] +pub extern "C" fn ChainParameters_set_best_block(this_ptr: &mut ChainParameters, mut val: crate::lightning::chain::BestBlock) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.best_block = *unsafe { Box::from_raw(val.take_inner()) }; +} +/// Constructs a new ChainParameters given each field +#[must_use] +#[no_mangle] +pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut best_block_arg: crate::lightning::chain::BestBlock) -> ChainParameters { + ChainParameters { inner: ObjOps::heap_alloc(nativeChainParameters { + network: network_arg.into_bitcoin(), + best_block: *unsafe { Box::from_raw(best_block_arg.take_inner()) }, + }), is_owned: true } +} +impl Clone for ChainParameters { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeChainParameters>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ChainParameters_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChainParameters)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the ChainParameters +pub extern "C" fn ChainParameters_clone(orig: &ChainParameters) -> ChainParameters { + orig.clone() +} +/// The amount of time in blocks we require our counterparty wait to claim their money (ie time +/// between when we, or our watchtower, must check for them having broadcast a theft transaction). +/// +/// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`] +/// +/// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay + +#[no_mangle] +pub static BREAKDOWN_TIMEOUT: u16 = lightning::ln::channelmanager::BREAKDOWN_TIMEOUT; +/// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound +/// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour. +/// +/// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`] +/// +/// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta + +#[no_mangle] +pub static MIN_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA; +/// Minimum CLTV difference between the current block height and received inbound payments. +/// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least +/// this value. + +#[no_mangle] +pub static MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA; + +use lightning::ln::channelmanager::CounterpartyForwardingInfo as nativeCounterpartyForwardingInfoImport; +pub(crate) type nativeCounterpartyForwardingInfo = nativeCounterpartyForwardingInfoImport; + +/// Information needed for constructing an invoice route hint for this channel. +#[must_use] +#[repr(C)] +pub struct CounterpartyForwardingInfo { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeCounterpartyForwardingInfo, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for CounterpartyForwardingInfo { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeCounterpartyForwardingInfo>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } -/// Frees any resources used by the ChainParameters, if is_owned is set and inner is non-NULL. +/// Frees any resources used by the CounterpartyForwardingInfo, if is_owned is set and inner is non-NULL. #[no_mangle] -pub extern "C" fn ChainParameters_free(this_obj: ChainParameters) { } +pub extern "C" fn CounterpartyForwardingInfo_free(this_obj: CounterpartyForwardingInfo) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainParameters); } +pub(crate) extern "C" fn CounterpartyForwardingInfo_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeCounterpartyForwardingInfo) }; } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy -impl ChainParameters { - pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters { +impl CounterpartyForwardingInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativeCounterpartyForwardingInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCounterpartyForwardingInfo { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeCounterpartyForwardingInfo { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } -/// The network for determining the `chain_hash` in Lightning messages. +/// Base routing fee in millisatoshis. #[no_mangle] -pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.network; - crate::bitcoin::network::Network::from_bitcoin(inner_val) +pub extern "C" fn CounterpartyForwardingInfo_get_fee_base_msat(this_ptr: &CounterpartyForwardingInfo) -> u32 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_base_msat; + *inner_val } -/// The network for determining the `chain_hash` in Lightning messages. +/// Base routing fee in millisatoshis. #[no_mangle] -pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) { - unsafe { &mut *this_ptr.inner }.network = val.into_bitcoin(); +pub extern "C" fn CounterpartyForwardingInfo_set_fee_base_msat(this_ptr: &mut CounterpartyForwardingInfo, mut val: u32) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_base_msat = val; } -/// The hash and height of the latest block successfully connected. -/// -/// Used to track on-chain channel funding outputs and send payments with reliable timelocks. +/// Amount in millionths of a satoshi the channel will charge per transferred satoshi. #[no_mangle] -pub extern "C" fn ChainParameters_get_best_block(this_ptr: &ChainParameters) -> crate::lightning::chain::BestBlock { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.best_block; - crate::lightning::chain::BestBlock { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } +pub extern "C" fn CounterpartyForwardingInfo_get_fee_proportional_millionths(this_ptr: &CounterpartyForwardingInfo) -> u32 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_proportional_millionths; + *inner_val } -/// The hash and height of the latest block successfully connected. -/// -/// Used to track on-chain channel funding outputs and send payments with reliable timelocks. +/// Amount in millionths of a satoshi the channel will charge per transferred satoshi. #[no_mangle] -pub extern "C" fn ChainParameters_set_best_block(this_ptr: &mut ChainParameters, mut val: crate::lightning::chain::BestBlock) { - unsafe { &mut *this_ptr.inner }.best_block = *unsafe { Box::from_raw(val.take_inner()) }; +pub extern "C" fn CounterpartyForwardingInfo_set_fee_proportional_millionths(this_ptr: &mut CounterpartyForwardingInfo, mut val: u32) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_proportional_millionths = val; } -/// Constructs a new ChainParameters given each field -#[must_use] +/// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart, +/// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s +/// `cltv_expiry_delta` for more details. #[no_mangle] -pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut best_block_arg: crate::lightning::chain::BestBlock) -> ChainParameters { - ChainParameters { inner: Box::into_raw(Box::new(nativeChainParameters { - network: network_arg.into_bitcoin(), - best_block: *unsafe { Box::from_raw(best_block_arg.take_inner()) }, - })), is_owned: true } +pub extern "C" fn CounterpartyForwardingInfo_get_cltv_expiry_delta(this_ptr: &CounterpartyForwardingInfo) -> u16 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; + *inner_val } -impl Clone for ChainParameters { +/// The minimum difference in cltv_expiry between an ingoing HTLC and its outgoing counterpart, +/// such that the outgoing HTLC is forwardable to this counterparty. See `msgs::ChannelUpdate`'s +/// `cltv_expiry_delta` for more details. +#[no_mangle] +pub extern "C" fn CounterpartyForwardingInfo_set_cltv_expiry_delta(this_ptr: &mut CounterpartyForwardingInfo, mut val: u16) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; +} +/// Constructs a new CounterpartyForwardingInfo given each field +#[must_use] +#[no_mangle] +pub extern "C" fn CounterpartyForwardingInfo_new(mut fee_base_msat_arg: u32, mut fee_proportional_millionths_arg: u32, mut cltv_expiry_delta_arg: u16) -> CounterpartyForwardingInfo { + CounterpartyForwardingInfo { inner: ObjOps::heap_alloc(nativeCounterpartyForwardingInfo { + fee_base_msat: fee_base_msat_arg, + fee_proportional_millionths: fee_proportional_millionths_arg, + cltv_expiry_delta: cltv_expiry_delta_arg, + }), is_owned: true } +} +impl Clone for CounterpartyForwardingInfo { fn clone(&self) -> Self { Self { - inner: if <*mut nativeChainParameters>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeCounterpartyForwardingInfo>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn ChainParameters_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChainParameters)).clone() })) as *mut c_void +pub(crate) extern "C" fn CounterpartyForwardingInfo_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeCounterpartyForwardingInfo)).clone() })) as *mut c_void } #[no_mangle] -/// Creates a copy of the ChainParameters -pub extern "C" fn ChainParameters_clone(orig: &ChainParameters) -> ChainParameters { +/// Creates a copy of the CounterpartyForwardingInfo +pub extern "C" fn CounterpartyForwardingInfo_clone(orig: &CounterpartyForwardingInfo) -> CounterpartyForwardingInfo { orig.clone() } -/// The amount of time in blocks we require our counterparty wait to claim their money (ie time -/// between when we, or our watchtower, must check for them having broadcast a theft transaction). -/// -/// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`] -/// -/// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay - -#[no_mangle] -pub static BREAKDOWN_TIMEOUT: u16 = lightning::ln::channelmanager::BREAKDOWN_TIMEOUT; -/// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound -/// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour. -/// -/// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`] -/// -/// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta - -#[no_mangle] -pub static MIN_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA; -/// Minimum CLTV difference between the current block height and received inbound payments. -/// Invoices generated for payment to us must set their `min_final_cltv_expiry` field to at least -/// this value. - -#[no_mangle] -pub static MIN_FINAL_CLTV_EXPIRY: u32 = lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY; +/// Get a string which allows debug introspection of a CounterpartyForwardingInfo object +pub extern "C" fn CounterpartyForwardingInfo_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::CounterpartyForwardingInfo }).into()} use lightning::ln::channelmanager::ChannelCounterparty as nativeChannelCounterpartyImport; -type nativeChannelCounterparty = nativeChannelCounterpartyImport; +pub(crate) type nativeChannelCounterparty = nativeChannelCounterpartyImport; /// Channel parameters which apply to our counterparty. These are split out from [`ChannelDetails`] /// to better separate parameters. @@ -253,7 +1287,7 @@ pub struct ChannelCounterparty { impl Drop for ChannelCounterparty { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelCounterparty>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -262,44 +1296,50 @@ impl Drop for ChannelCounterparty { pub extern "C" fn ChannelCounterparty_free(this_obj: ChannelCounterparty) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelCounterparty_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelCounterparty); } +pub(crate) extern "C" fn ChannelCounterparty_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelCounterparty) }; } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelCounterparty { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelCounterparty { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelCounterparty { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeChannelCounterparty { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } /// The node_id of our counterparty #[no_mangle] pub extern "C" fn ChannelCounterparty_get_node_id(this_ptr: &ChannelCounterparty) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id; crate::c_types::PublicKey::from_rust(&inner_val) } /// The node_id of our counterparty #[no_mangle] pub extern "C" fn ChannelCounterparty_set_node_id(this_ptr: &mut ChannelCounterparty, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.node_id = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id = val.into_rust(); } /// The Features the channel counterparty provided upon last connection. /// Useful for routing as it is the most up-to-date copy of the counterparty's features and /// many routing-relevant features are present in the init context. #[no_mangle] pub extern "C" fn ChannelCounterparty_get_features(this_ptr: &ChannelCounterparty) -> crate::lightning::ln::features::InitFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features; - crate::lightning::ln::features::InitFeatures { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().features; + crate::lightning::ln::features::InitFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::ln::features::InitFeatures<>) as *mut _) }, is_owned: false } } /// The Features the channel counterparty provided upon last connection. /// Useful for routing as it is the most up-to-date copy of the counterparty's features and /// many routing-relevant features are present in the init context. #[no_mangle] pub extern "C" fn ChannelCounterparty_set_features(this_ptr: &mut ChannelCounterparty, mut val: crate::lightning::ln::features::InitFeatures) { - unsafe { &mut *this_ptr.inner }.features = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.features = *unsafe { Box::from_raw(val.take_inner()) }; } /// The value, in satoshis, that must always be held in the channel for our counterparty. This /// value ensures that if our counterparty broadcasts a revoked state, we can punish them by @@ -310,7 +1350,7 @@ pub extern "C" fn ChannelCounterparty_set_features(this_ptr: &mut ChannelCounter /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat #[no_mangle] pub extern "C" fn ChannelCounterparty_get_unspendable_punishment_reserve(this_ptr: &ChannelCounterparty) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve; + let mut inner_val = &mut this_ptr.get_native_mut_ref().unspendable_punishment_reserve; *inner_val } /// The value, in satoshis, that must always be held in the channel for our counterparty. This @@ -322,13 +1362,80 @@ pub extern "C" fn ChannelCounterparty_get_unspendable_punishment_reserve(this_pt /// [`inbound_capacity_msat`]: ChannelDetails::inbound_capacity_msat #[no_mangle] pub extern "C" fn ChannelCounterparty_set_unspendable_punishment_reserve(this_ptr: &mut ChannelCounterparty, mut val: u64) { - unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.unspendable_punishment_reserve = val; +} +/// Information on the fees and requirements that the counterparty requires when forwarding +/// payments to us through this channel. +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelCounterparty_get_forwarding_info(this_ptr: &ChannelCounterparty) -> crate::lightning::ln::channelmanager::CounterpartyForwardingInfo { + let mut inner_val = &mut this_ptr.get_native_mut_ref().forwarding_info; + let mut local_inner_val = crate::lightning::ln::channelmanager::CounterpartyForwardingInfo { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::channelmanager::CounterpartyForwardingInfo<>) as *mut _ }, is_owned: false }; + local_inner_val +} +/// Information on the fees and requirements that the counterparty requires when forwarding +/// payments to us through this channel. +/// +/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelCounterparty_set_forwarding_info(this_ptr: &mut ChannelCounterparty, mut val: crate::lightning::ln::channelmanager::CounterpartyForwardingInfo) { + let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.forwarding_info = local_val; +} +/// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field +/// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message +/// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107. +#[no_mangle] +pub extern "C" fn ChannelCounterparty_get_outbound_htlc_minimum_msat(this_ptr: &ChannelCounterparty) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().outbound_htlc_minimum_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The smallest value HTLC (in msat) the remote peer will accept, for this channel. This field +/// is only `None` before we have received either the `OpenChannel` or `AcceptChannel` message +/// from the remote peer, or for `ChannelCounterparty` objects serialized prior to LDK 0.0.107. +#[no_mangle] +pub extern "C" fn ChannelCounterparty_set_outbound_htlc_minimum_msat(this_ptr: &mut ChannelCounterparty, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outbound_htlc_minimum_msat = local_val; +} +/// The largest value HTLC (in msat) the remote peer currently will accept, for this channel. +#[no_mangle] +pub extern "C" fn ChannelCounterparty_get_outbound_htlc_maximum_msat(this_ptr: &ChannelCounterparty) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().outbound_htlc_maximum_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The largest value HTLC (in msat) the remote peer currently will accept, for this channel. +#[no_mangle] +pub extern "C" fn ChannelCounterparty_set_outbound_htlc_maximum_msat(this_ptr: &mut ChannelCounterparty, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outbound_htlc_maximum_msat = local_val; +} +/// Constructs a new ChannelCounterparty given each field +/// +/// Note that forwarding_info_arg (or a relevant inner pointer) may be NULL or all-0s to represent None +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelCounterparty_new(mut node_id_arg: crate::c_types::PublicKey, mut features_arg: crate::lightning::ln::features::InitFeatures, mut unspendable_punishment_reserve_arg: u64, mut forwarding_info_arg: crate::lightning::ln::channelmanager::CounterpartyForwardingInfo, mut outbound_htlc_minimum_msat_arg: crate::c_types::derived::COption_u64Z, mut outbound_htlc_maximum_msat_arg: crate::c_types::derived::COption_u64Z) -> ChannelCounterparty { + let mut local_forwarding_info_arg = if forwarding_info_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(forwarding_info_arg.take_inner()) } }) }; + let mut local_outbound_htlc_minimum_msat_arg = if outbound_htlc_minimum_msat_arg.is_some() { Some( { outbound_htlc_minimum_msat_arg.take() }) } else { None }; + let mut local_outbound_htlc_maximum_msat_arg = if outbound_htlc_maximum_msat_arg.is_some() { Some( { outbound_htlc_maximum_msat_arg.take() }) } else { None }; + ChannelCounterparty { inner: ObjOps::heap_alloc(nativeChannelCounterparty { + node_id: node_id_arg.into_rust(), + features: *unsafe { Box::from_raw(features_arg.take_inner()) }, + unspendable_punishment_reserve: unspendable_punishment_reserve_arg, + forwarding_info: local_forwarding_info_arg, + outbound_htlc_minimum_msat: local_outbound_htlc_minimum_msat_arg, + outbound_htlc_maximum_msat: local_outbound_htlc_maximum_msat_arg, + }), is_owned: true } } impl Clone for ChannelCounterparty { fn clone(&self) -> Self { Self { - inner: if <*mut nativeChannelCounterparty>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeChannelCounterparty>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -336,18 +1443,21 @@ impl Clone for ChannelCounterparty { #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method pub(crate) extern "C" fn ChannelCounterparty_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelCounterparty)).clone() })) as *mut c_void + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelCounterparty)).clone() })) as *mut c_void } #[no_mangle] /// Creates a copy of the ChannelCounterparty pub extern "C" fn ChannelCounterparty_clone(orig: &ChannelCounterparty) -> ChannelCounterparty { orig.clone() } +/// Get a string which allows debug introspection of a ChannelCounterparty object +pub extern "C" fn ChannelCounterparty_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::ChannelCounterparty }).into()} use lightning::ln::channelmanager::ChannelDetails as nativeChannelDetailsImport; -type nativeChannelDetails = nativeChannelDetailsImport; +pub(crate) type nativeChannelDetails = nativeChannelDetailsImport; -/// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels +/// Details of a channel, as returned by [`ChannelManager::list_channels`] and [`ChannelManager::list_usable_channels`] #[must_use] #[repr(C)] pub struct ChannelDetails { @@ -366,7 +1476,7 @@ pub struct ChannelDetails { impl Drop for ChannelDetails { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelDetails>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -375,16 +1485,22 @@ impl Drop for ChannelDetails { pub extern "C" fn ChannelDetails_free(this_obj: ChannelDetails) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelDetails); } +pub(crate) extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelDetails) }; } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelDetails { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelDetails { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelDetails { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeChannelDetails { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } @@ -394,8 +1510,8 @@ impl ChannelDetails { /// lifetime of the channel. #[no_mangle] pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; - inner_val + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; + &inner_val.0 } /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes, /// thereafter this is the txid of the funding transaction xor the funding transaction output). @@ -403,18 +1519,18 @@ pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *c /// lifetime of the channel. #[no_mangle] pub extern "C" fn ChannelDetails_set_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.channel_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = ::lightning::ln::ChannelId(val.data); } /// Parameters which apply to our counterparty. See individual fields for more information. #[no_mangle] pub extern "C" fn ChannelDetails_get_counterparty(this_ptr: &ChannelDetails) -> crate::lightning::ln::channelmanager::ChannelCounterparty { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty; - crate::lightning::ln::channelmanager::ChannelCounterparty { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty; + crate::lightning::ln::channelmanager::ChannelCounterparty { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::ln::channelmanager::ChannelCounterparty<>) as *mut _) }, is_owned: false } } /// Parameters which apply to our counterparty. See individual fields for more information. #[no_mangle] pub extern "C" fn ChannelDetails_set_counterparty(this_ptr: &mut ChannelDetails, mut val: crate::lightning::ln::channelmanager::ChannelCounterparty) { - unsafe { &mut *this_ptr.inner }.counterparty = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty = *unsafe { Box::from_raw(val.take_inner()) }; } /// The Channel's funding transaction output, if we've negotiated the funding transaction with /// our counterparty already. @@ -425,8 +1541,8 @@ pub extern "C" fn ChannelDetails_set_counterparty(this_ptr: &mut ChannelDetails, /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> crate::lightning::chain::transaction::OutPoint { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_txo; - let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { { (inner_val.as_ref().unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_txo; + let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::chain::transaction::OutPoint<>) as *mut _ }, is_owned: false }; local_inner_val } /// The Channel's funding transaction output, if we've negotiated the funding transaction with @@ -439,33 +1555,136 @@ pub extern "C" fn ChannelDetails_get_funding_txo(this_ptr: &ChannelDetails) -> c #[no_mangle] pub extern "C" fn ChannelDetails_set_funding_txo(this_ptr: &mut ChannelDetails, mut val: crate::lightning::chain::transaction::OutPoint) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.funding_txo = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_txo = local_val; +} +/// The features which this channel operates with. See individual features for more info. +/// +/// `None` until negotiation completes and the channel type is finalized. +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelDetails_get_channel_type(this_ptr: &ChannelDetails) -> crate::lightning::ln::features::ChannelTypeFeatures { + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_type; + let mut local_inner_val = crate::lightning::ln::features::ChannelTypeFeatures { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::features::ChannelTypeFeatures<>) as *mut _ }, is_owned: false }; + local_inner_val +} +/// The features which this channel operates with. See individual features for more info. +/// +/// `None` until negotiation completes and the channel type is finalized. +/// +/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelDetails_set_channel_type(this_ptr: &mut ChannelDetails, mut val: crate::lightning::ln::features::ChannelTypeFeatures) { + let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_type = local_val; } /// The position of the funding transaction in the chain. None if the funding transaction has /// not yet been confirmed and the channel fully opened. +/// +/// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound +/// payments instead of this. See [`get_inbound_payment_scid`]. +/// +/// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may +/// be used in place of this in outbound routes. See [`get_outbound_payment_scid`]. +/// +/// [`inbound_scid_alias`]: Self::inbound_scid_alias +/// [`outbound_scid_alias`]: Self::outbound_scid_alias +/// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid +/// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid +/// [`confirmations_required`]: Self::confirmations_required #[no_mangle] pub extern "C" fn ChannelDetails_get_short_channel_id(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; - let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { { crate::c_types::derived::COption_u64Z::Some(inner_val.unwrap()) } }; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; local_inner_val } /// The position of the funding transaction in the chain. None if the funding transaction has /// not yet been confirmed and the channel fully opened. +/// +/// Note that if [`inbound_scid_alias`] is set, it must be used for invoices and inbound +/// payments instead of this. See [`get_inbound_payment_scid`]. +/// +/// For channels with [`confirmations_required`] set to `Some(0)`, [`outbound_scid_alias`] may +/// be used in place of this in outbound routes. See [`get_outbound_payment_scid`]. +/// +/// [`inbound_scid_alias`]: Self::inbound_scid_alias +/// [`outbound_scid_alias`]: Self::outbound_scid_alias +/// [`get_inbound_payment_scid`]: Self::get_inbound_payment_scid +/// [`get_outbound_payment_scid`]: Self::get_outbound_payment_scid +/// [`confirmations_required`]: Self::confirmations_required #[no_mangle] pub extern "C" fn ChannelDetails_set_short_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; - unsafe { &mut *this_ptr.inner }.short_channel_id = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = local_val; +} +/// An optional [`short_channel_id`] alias for this channel, randomly generated by us and +/// usable in place of [`short_channel_id`] to reference the channel in outbound routes when +/// the channel has not yet been confirmed (as long as [`confirmations_required`] is +/// `Some(0)`). +/// +/// This will be `None` as long as the channel is not available for routing outbound payments. +/// +/// [`short_channel_id`]: Self::short_channel_id +/// [`confirmations_required`]: Self::confirmations_required +#[no_mangle] +pub extern "C" fn ChannelDetails_get_outbound_scid_alias(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().outbound_scid_alias; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// An optional [`short_channel_id`] alias for this channel, randomly generated by us and +/// usable in place of [`short_channel_id`] to reference the channel in outbound routes when +/// the channel has not yet been confirmed (as long as [`confirmations_required`] is +/// `Some(0)`). +/// +/// This will be `None` as long as the channel is not available for routing outbound payments. +/// +/// [`short_channel_id`]: Self::short_channel_id +/// [`confirmations_required`]: Self::confirmations_required +#[no_mangle] +pub extern "C" fn ChannelDetails_set_outbound_scid_alias(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outbound_scid_alias = local_val; +} +/// An optional [`short_channel_id`] alias for this channel, randomly generated by our +/// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our +/// counterparty will recognize the alias provided here in place of the [`short_channel_id`] +/// when they see a payment to be routed to us. +/// +/// Our counterparty may choose to rotate this value at any time, though will always recognize +/// previous values for inbound payment forwarding. +/// +/// [`short_channel_id`]: Self::short_channel_id +#[no_mangle] +pub extern "C" fn ChannelDetails_get_inbound_scid_alias(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_scid_alias; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// An optional [`short_channel_id`] alias for this channel, randomly generated by our +/// counterparty and usable in place of [`short_channel_id`] in invoice route hints. Our +/// counterparty will recognize the alias provided here in place of the [`short_channel_id`] +/// when they see a payment to be routed to us. +/// +/// Our counterparty may choose to rotate this value at any time, though will always recognize +/// previous values for inbound payment forwarding. +/// +/// [`short_channel_id`]: Self::short_channel_id +#[no_mangle] +pub extern "C" fn ChannelDetails_set_inbound_scid_alias(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_scid_alias = local_val; } /// The value, in satoshis, of this channel as appears in the funding output #[no_mangle] pub extern "C" fn ChannelDetails_get_channel_value_satoshis(this_ptr: &ChannelDetails) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_value_satoshis; *inner_val } /// The value, in satoshis, of this channel as appears in the funding output #[no_mangle] pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut ChannelDetails, mut val: u64) { - unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val; } /// The value, in satoshis, that must always be held in the channel for us. This value ensures /// that if we broadcast a revoked state, our counterparty can punish us by claiming at least @@ -478,8 +1697,8 @@ pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut Chann /// [`outbound_capacity_msat`]: ChannelDetails::outbound_capacity_msat #[no_mangle] pub extern "C" fn ChannelDetails_get_unspendable_punishment_reserve(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve; - let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { { crate::c_types::derived::COption_u64Z::Some(inner_val.unwrap()) } }; + let mut inner_val = &mut this_ptr.get_native_mut_ref().unspendable_punishment_reserve; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; local_inner_val } /// The value, in satoshis, that must always be held in the channel for us. This value ensures @@ -494,46 +1713,154 @@ pub extern "C" fn ChannelDetails_get_unspendable_punishment_reserve(this_ptr: &C #[no_mangle] pub extern "C" fn ChannelDetails_set_unspendable_punishment_reserve(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; - unsafe { &mut *this_ptr.inner }.unspendable_punishment_reserve = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.unspendable_punishment_reserve = local_val; +} +/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound +/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if +/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise +/// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects +/// serialized with LDK versions prior to 0.0.113. +/// +/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel +/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel +/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels +#[no_mangle] +pub extern "C" fn ChannelDetails_get_user_channel_id(this_ptr: &ChannelDetails) -> crate::c_types::U128 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().user_channel_id; + inner_val.into() +} +/// The `user_channel_id` value passed in to [`ChannelManager::create_channel`] for outbound +/// channels, or to [`ChannelManager::accept_inbound_channel`] for inbound channels if +/// [`UserConfig::manually_accept_inbound_channels`] config flag is set to true. Otherwise +/// `user_channel_id` will be randomized for an inbound channel. This may be zero for objects +/// serialized with LDK versions prior to 0.0.113. +/// +/// [`ChannelManager::create_channel`]: crate::ln::channelmanager::ChannelManager::create_channel +/// [`ChannelManager::accept_inbound_channel`]: crate::ln::channelmanager::ChannelManager::accept_inbound_channel +/// [`UserConfig::manually_accept_inbound_channels`]: crate::util::config::UserConfig::manually_accept_inbound_channels +#[no_mangle] +pub extern "C" fn ChannelDetails_set_user_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::U128) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.user_channel_id = val.into(); +} +/// The currently negotiated fee rate denominated in satoshi per 1000 weight units, +/// which is applied to commitment and HTLC transactions. +/// +/// This value will be `None` for objects serialized with LDK versions prior to 0.0.115. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_feerate_sat_per_1000_weight(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u32Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().feerate_sat_per_1000_weight; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else { crate::c_types::derived::COption_u32Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The currently negotiated fee rate denominated in satoshi per 1000 weight units, +/// which is applied to commitment and HTLC transactions. +/// +/// This value will be `None` for objects serialized with LDK versions prior to 0.0.115. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_feerate_sat_per_1000_weight(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u32Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.feerate_sat_per_1000_weight = local_val; } -/// The user_id passed in to create_channel, or 0 if the channel was inbound. +/// Our total balance. This is the amount we would get if we close the channel. +/// This value is not exact. Due to various in-flight changes and feerate changes, exactly this +/// amount is not likely to be recoverable on close. +/// +/// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose +/// balance is not available for inclusion in new outbound HTLCs). This further does not include +/// any pending outgoing HTLCs which are awaiting some other resolution to be sent. +/// This does not consider any on-chain fees. +/// +/// See also [`ChannelDetails::outbound_capacity_msat`] #[no_mangle] -pub extern "C" fn ChannelDetails_get_user_id(this_ptr: &ChannelDetails) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.user_id; +pub extern "C" fn ChannelDetails_get_balance_msat(this_ptr: &ChannelDetails) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().balance_msat; *inner_val } -/// The user_id passed in to create_channel, or 0 if the channel was inbound. +/// Our total balance. This is the amount we would get if we close the channel. +/// This value is not exact. Due to various in-flight changes and feerate changes, exactly this +/// amount is not likely to be recoverable on close. +/// +/// This does not include any pending HTLCs which are not yet fully resolved (and, thus, whose +/// balance is not available for inclusion in new outbound HTLCs). This further does not include +/// any pending outgoing HTLCs which are awaiting some other resolution to be sent. +/// This does not consider any on-chain fees. +/// +/// See also [`ChannelDetails::outbound_capacity_msat`] #[no_mangle] -pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut val: u64) { - unsafe { &mut *this_ptr.inner }.user_id = val; +pub extern "C" fn ChannelDetails_set_balance_msat(this_ptr: &mut ChannelDetails, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.balance_msat = val; } /// The available outbound capacity for sending HTLCs to the remote peer. This does not include -/// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not +/// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not /// available for inclusion in new outbound HTLCs). This further does not include any pending /// outgoing HTLCs which are awaiting some other resolution to be sent. /// +/// See also [`ChannelDetails::balance_msat`] +/// /// This value is not exact. Due to various in-flight changes, feerate changes, and our /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we /// should be able to spend nearly this amount. #[no_mangle] pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outbound_capacity_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().outbound_capacity_msat; *inner_val } /// The available outbound capacity for sending HTLCs to the remote peer. This does not include -/// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not +/// any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not /// available for inclusion in new outbound HTLCs). This further does not include any pending /// outgoing HTLCs which are awaiting some other resolution to be sent. /// +/// See also [`ChannelDetails::balance_msat`] +/// /// This value is not exact. Due to various in-flight changes, feerate changes, and our /// conflict-avoidance policy, exactly this amount is not likely to be spendable. However, we /// should be able to spend nearly this amount. #[no_mangle] pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) { - unsafe { &mut *this_ptr.inner }.outbound_capacity_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outbound_capacity_msat = val; +} +/// The available outbound capacity for sending a single HTLC to the remote peer. This is +/// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by +/// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us +/// to use a limit as close as possible to the HTLC limit we can currently send. +/// +/// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`], +/// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`]. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_next_outbound_htlc_limit_msat(this_ptr: &ChannelDetails) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_outbound_htlc_limit_msat; + *inner_val +} +/// The available outbound capacity for sending a single HTLC to the remote peer. This is +/// similar to [`ChannelDetails::outbound_capacity_msat`] but it may be further restricted by +/// the current state and per-HTLC limit(s). This is intended for use when routing, allowing us +/// to use a limit as close as possible to the HTLC limit we can currently send. +/// +/// See also [`ChannelDetails::next_outbound_htlc_minimum_msat`], +/// [`ChannelDetails::balance_msat`], and [`ChannelDetails::outbound_capacity_msat`]. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_next_outbound_htlc_limit_msat(this_ptr: &mut ChannelDetails, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_outbound_htlc_limit_msat = val; +} +/// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of +/// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than +/// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a +/// route which is valid. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_next_outbound_htlc_minimum_msat(this_ptr: &ChannelDetails) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_outbound_htlc_minimum_msat; + *inner_val +} +/// The minimum value for sending a single HTLC to the remote peer. This is the equivalent of +/// [`ChannelDetails::next_outbound_htlc_limit_msat`] but represents a lower-bound, rather than +/// an upper-bound. This is intended for use when routing, allowing us to ensure we pick a +/// route which is valid. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_next_outbound_htlc_minimum_msat(this_ptr: &mut ChannelDetails, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_outbound_htlc_minimum_msat = val; } /// The available inbound capacity for the remote peer to send HTLCs to us. This does not -/// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not +/// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not /// available for inclusion in new inbound HTLCs). /// Note that there are some corner cases not fully handled here, so the actual available /// inbound capacity may be slightly higher than this. @@ -543,11 +1870,11 @@ pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut Chann /// However, our counterparty should be able to spend nearly this amount. #[no_mangle] pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.inbound_capacity_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_capacity_msat; *inner_val } /// The available inbound capacity for the remote peer to send HTLCs to us. This does not -/// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not +/// include any pending HTLCs which are not yet fully resolved (and, thus, whose balance is not /// available for inclusion in new inbound HTLCs). /// Note that there are some corner cases not fully handled here, so the actual available /// inbound capacity may be slightly higher than this. @@ -557,7 +1884,7 @@ pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDet /// However, our counterparty should be able to spend nearly this amount. #[no_mangle] pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) { - unsafe { &mut *this_ptr.inner }.inbound_capacity_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_capacity_msat = val; } /// The number of required confirmations on the funding transaction before the funding will be /// considered \"locked\". This number is selected by the channel fundee (i.e. us if @@ -572,8 +1899,8 @@ pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut Channe /// [`ChannelHandshakeLimits::max_minimum_depth`]: crate::util::config::ChannelHandshakeLimits::max_minimum_depth #[no_mangle] pub extern "C" fn ChannelDetails_get_confirmations_required(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u32Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.confirmations_required; - let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else { { crate::c_types::derived::COption_u32Z::Some(inner_val.unwrap()) } }; + let mut inner_val = &mut this_ptr.get_native_mut_ref().confirmations_required; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else { crate::c_types::derived::COption_u32Z::Some( { inner_val.unwrap() }) }; local_inner_val } /// The number of required confirmations on the funding transaction before the funding will be @@ -590,7 +1917,24 @@ pub extern "C" fn ChannelDetails_get_confirmations_required(this_ptr: &ChannelDe #[no_mangle] pub extern "C" fn ChannelDetails_set_confirmations_required(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u32Z) { let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; - unsafe { &mut *this_ptr.inner }.confirmations_required = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.confirmations_required = local_val; +} +/// The current number of confirmations on the funding transaction. +/// +/// This value will be `None` for objects serialized with LDK versions prior to 0.0.113. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_confirmations(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u32Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().confirmations; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u32Z::None } else { crate::c_types::derived::COption_u32Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The current number of confirmations on the funding transaction. +/// +/// This value will be `None` for objects serialized with LDK versions prior to 0.0.113. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_confirmations(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u32Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.confirmations = local_val; } /// The number of blocks (after our commitment transaction confirms) that we will need to wait /// until we can claim our funds after we force-close the channel. During this time our @@ -601,8 +1945,8 @@ pub extern "C" fn ChannelDetails_set_confirmations_required(this_ptr: &mut Chann /// This value will be `None` for outbound channels until the counterparty accepts the channel. #[no_mangle] pub extern "C" fn ChannelDetails_get_force_close_spend_delay(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u16Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.force_close_spend_delay; - let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u16Z::None } else { { crate::c_types::derived::COption_u16Z::Some(inner_val.unwrap()) } }; + let mut inner_val = &mut this_ptr.get_native_mut_ref().force_close_spend_delay; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u16Z::None } else { crate::c_types::derived::COption_u16Z::Some( { inner_val.unwrap() }) }; local_inner_val } /// The number of blocks (after our commitment transaction confirms) that we will need to wait @@ -615,102 +1959,193 @@ pub extern "C" fn ChannelDetails_get_force_close_spend_delay(this_ptr: &ChannelD #[no_mangle] pub extern "C" fn ChannelDetails_set_force_close_spend_delay(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u16Z) { let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; - unsafe { &mut *this_ptr.inner }.force_close_spend_delay = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.force_close_spend_delay = local_val; } /// True if the channel was initiated (and thus funded) by us. #[no_mangle] pub extern "C" fn ChannelDetails_get_is_outbound(this_ptr: &ChannelDetails) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_outbound; + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_outbound; *inner_val } /// True if the channel was initiated (and thus funded) by us. #[no_mangle] pub extern "C" fn ChannelDetails_set_is_outbound(this_ptr: &mut ChannelDetails, mut val: bool) { - unsafe { &mut *this_ptr.inner }.is_outbound = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_outbound = val; } -/// True if the channel is confirmed, funding_locked messages have been exchanged, and the -/// channel is not currently being shut down. `funding_locked` message exchange implies the +/// True if the channel is confirmed, channel_ready messages have been exchanged, and the +/// channel is not currently being shut down. `channel_ready` message exchange implies the /// required confirmation count has been reached (and we were connected to the peer at some /// point after the funding transaction received enough confirmations). The required /// confirmation count is provided in [`confirmations_required`]. /// /// [`confirmations_required`]: ChannelDetails::confirmations_required #[no_mangle] -pub extern "C" fn ChannelDetails_get_is_funding_locked(this_ptr: &ChannelDetails) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_funding_locked; +pub extern "C" fn ChannelDetails_get_is_channel_ready(this_ptr: &ChannelDetails) -> bool { + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_channel_ready; *inner_val } -/// True if the channel is confirmed, funding_locked messages have been exchanged, and the -/// channel is not currently being shut down. `funding_locked` message exchange implies the +/// True if the channel is confirmed, channel_ready messages have been exchanged, and the +/// channel is not currently being shut down. `channel_ready` message exchange implies the /// required confirmation count has been reached (and we were connected to the peer at some /// point after the funding transaction received enough confirmations). The required /// confirmation count is provided in [`confirmations_required`]. /// /// [`confirmations_required`]: ChannelDetails::confirmations_required #[no_mangle] -pub extern "C" fn ChannelDetails_set_is_funding_locked(this_ptr: &mut ChannelDetails, mut val: bool) { - unsafe { &mut *this_ptr.inner }.is_funding_locked = val; +pub extern "C" fn ChannelDetails_set_is_channel_ready(this_ptr: &mut ChannelDetails, mut val: bool) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_channel_ready = val; +} +/// The stage of the channel's shutdown. +/// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116. +/// +/// Returns a copy of the field. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_channel_shutdown_state(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_ChannelShutdownStateZ { + let mut inner_val = this_ptr.get_native_mut_ref().channel_shutdown_state.clone(); + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_ChannelShutdownStateZ::None } else { crate::c_types::derived::COption_ChannelShutdownStateZ::Some( { crate::lightning::ln::channelmanager::ChannelShutdownState::native_into(inner_val.unwrap()) }) }; + local_inner_val +} +/// The stage of the channel's shutdown. +/// `None` for `ChannelDetails` serialized on LDK versions prior to 0.0.116. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_channel_shutdown_state(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_ChannelShutdownStateZ) { + let mut local_val = { /*val*/ let val_opt = val; if val_opt.is_none() { None } else { Some({ { { val_opt.take() }.into_native() }})} }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_shutdown_state = local_val; } -/// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b) +/// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b) /// the peer is connected, and (c) the channel is not currently negotiating a shutdown. /// -/// This is a strict superset of `is_funding_locked`. +/// This is a strict superset of `is_channel_ready`. #[no_mangle] pub extern "C" fn ChannelDetails_get_is_usable(this_ptr: &ChannelDetails) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_usable; + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_usable; *inner_val } -/// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b) +/// True if the channel is (a) confirmed and channel_ready messages have been exchanged, (b) /// the peer is connected, and (c) the channel is not currently negotiating a shutdown. /// -/// This is a strict superset of `is_funding_locked`. +/// This is a strict superset of `is_channel_ready`. #[no_mangle] pub extern "C" fn ChannelDetails_set_is_usable(this_ptr: &mut ChannelDetails, mut val: bool) { - unsafe { &mut *this_ptr.inner }.is_usable = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_usable = val; } /// True if this channel is (or will be) publicly-announced. #[no_mangle] pub extern "C" fn ChannelDetails_get_is_public(this_ptr: &ChannelDetails) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_public; + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_public; *inner_val } /// True if this channel is (or will be) publicly-announced. #[no_mangle] pub extern "C" fn ChannelDetails_set_is_public(this_ptr: &mut ChannelDetails, mut val: bool) { - unsafe { &mut *this_ptr.inner }.is_public = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_public = val; +} +/// The smallest value HTLC (in msat) we will accept, for this channel. This field +/// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107 +#[no_mangle] +pub extern "C" fn ChannelDetails_get_inbound_htlc_minimum_msat(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_htlc_minimum_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The smallest value HTLC (in msat) we will accept, for this channel. This field +/// is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.107 +#[no_mangle] +pub extern "C" fn ChannelDetails_set_inbound_htlc_minimum_msat(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_htlc_minimum_msat = local_val; +} +/// The largest value HTLC (in msat) we currently will accept, for this channel. +#[no_mangle] +pub extern "C" fn ChannelDetails_get_inbound_htlc_maximum_msat(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_htlc_maximum_msat; + let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) }; + local_inner_val +} +/// The largest value HTLC (in msat) we currently will accept, for this channel. +#[no_mangle] +pub extern "C" fn ChannelDetails_set_inbound_htlc_maximum_msat(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) { + let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_htlc_maximum_msat = local_val; +} +/// Set of configurable parameters that affect channel operation. +/// +/// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109. +/// +/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelDetails_get_config(this_ptr: &ChannelDetails) -> crate::lightning::util::config::ChannelConfig { + let mut inner_val = &mut this_ptr.get_native_mut_ref().config; + let mut local_inner_val = crate::lightning::util::config::ChannelConfig { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::util::config::ChannelConfig<>) as *mut _ }, is_owned: false }; + local_inner_val +} +/// Set of configurable parameters that affect channel operation. +/// +/// This field is only `None` for `ChannelDetails` objects serialized prior to LDK 0.0.109. +/// +/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None +#[no_mangle] +pub extern "C" fn ChannelDetails_set_config(this_ptr: &mut ChannelDetails, mut val: crate::lightning::util::config::ChannelConfig) { + let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.config = local_val; } /// Constructs a new ChannelDetails given each field +/// +/// Note that funding_txo_arg (or a relevant inner pointer) may be NULL or all-0s to represent None +/// Note that channel_type_arg (or a relevant inner pointer) may be NULL or all-0s to represent None +/// Note that config_arg (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] -pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut counterparty_arg: crate::lightning::ln::channelmanager::ChannelCounterparty, mut funding_txo_arg: crate::lightning::chain::transaction::OutPoint, mut short_channel_id_arg: crate::c_types::derived::COption_u64Z, mut channel_value_satoshis_arg: u64, mut unspendable_punishment_reserve_arg: crate::c_types::derived::COption_u64Z, mut user_id_arg: u64, mut outbound_capacity_msat_arg: u64, mut inbound_capacity_msat_arg: u64, mut confirmations_required_arg: crate::c_types::derived::COption_u32Z, mut force_close_spend_delay_arg: crate::c_types::derived::COption_u16Z, mut is_outbound_arg: bool, mut is_funding_locked_arg: bool, mut is_usable_arg: bool, mut is_public_arg: bool) -> ChannelDetails { +pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut counterparty_arg: crate::lightning::ln::channelmanager::ChannelCounterparty, mut funding_txo_arg: crate::lightning::chain::transaction::OutPoint, mut channel_type_arg: crate::lightning::ln::features::ChannelTypeFeatures, mut short_channel_id_arg: crate::c_types::derived::COption_u64Z, mut outbound_scid_alias_arg: crate::c_types::derived::COption_u64Z, mut inbound_scid_alias_arg: crate::c_types::derived::COption_u64Z, mut channel_value_satoshis_arg: u64, mut unspendable_punishment_reserve_arg: crate::c_types::derived::COption_u64Z, mut user_channel_id_arg: crate::c_types::U128, mut feerate_sat_per_1000_weight_arg: crate::c_types::derived::COption_u32Z, mut balance_msat_arg: u64, mut outbound_capacity_msat_arg: u64, mut next_outbound_htlc_limit_msat_arg: u64, mut next_outbound_htlc_minimum_msat_arg: u64, mut inbound_capacity_msat_arg: u64, mut confirmations_required_arg: crate::c_types::derived::COption_u32Z, mut confirmations_arg: crate::c_types::derived::COption_u32Z, mut force_close_spend_delay_arg: crate::c_types::derived::COption_u16Z, mut is_outbound_arg: bool, mut is_channel_ready_arg: bool, mut channel_shutdown_state_arg: crate::c_types::derived::COption_ChannelShutdownStateZ, mut is_usable_arg: bool, mut is_public_arg: bool, mut inbound_htlc_minimum_msat_arg: crate::c_types::derived::COption_u64Z, mut inbound_htlc_maximum_msat_arg: crate::c_types::derived::COption_u64Z, mut config_arg: crate::lightning::util::config::ChannelConfig) -> ChannelDetails { let mut local_funding_txo_arg = if funding_txo_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(funding_txo_arg.take_inner()) } }) }; + let mut local_channel_type_arg = if channel_type_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(channel_type_arg.take_inner()) } }) }; let mut local_short_channel_id_arg = if short_channel_id_arg.is_some() { Some( { short_channel_id_arg.take() }) } else { None }; + let mut local_outbound_scid_alias_arg = if outbound_scid_alias_arg.is_some() { Some( { outbound_scid_alias_arg.take() }) } else { None }; + let mut local_inbound_scid_alias_arg = if inbound_scid_alias_arg.is_some() { Some( { inbound_scid_alias_arg.take() }) } else { None }; let mut local_unspendable_punishment_reserve_arg = if unspendable_punishment_reserve_arg.is_some() { Some( { unspendable_punishment_reserve_arg.take() }) } else { None }; + let mut local_feerate_sat_per_1000_weight_arg = if feerate_sat_per_1000_weight_arg.is_some() { Some( { feerate_sat_per_1000_weight_arg.take() }) } else { None }; let mut local_confirmations_required_arg = if confirmations_required_arg.is_some() { Some( { confirmations_required_arg.take() }) } else { None }; + let mut local_confirmations_arg = if confirmations_arg.is_some() { Some( { confirmations_arg.take() }) } else { None }; let mut local_force_close_spend_delay_arg = if force_close_spend_delay_arg.is_some() { Some( { force_close_spend_delay_arg.take() }) } else { None }; - ChannelDetails { inner: Box::into_raw(Box::new(nativeChannelDetails { - channel_id: channel_id_arg.data, + let mut local_channel_shutdown_state_arg = { /*channel_shutdown_state_arg*/ let channel_shutdown_state_arg_opt = channel_shutdown_state_arg; if channel_shutdown_state_arg_opt.is_none() { None } else { Some({ { { channel_shutdown_state_arg_opt.take() }.into_native() }})} }; + let mut local_inbound_htlc_minimum_msat_arg = if inbound_htlc_minimum_msat_arg.is_some() { Some( { inbound_htlc_minimum_msat_arg.take() }) } else { None }; + let mut local_inbound_htlc_maximum_msat_arg = if inbound_htlc_maximum_msat_arg.is_some() { Some( { inbound_htlc_maximum_msat_arg.take() }) } else { None }; + let mut local_config_arg = if config_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(config_arg.take_inner()) } }) }; + ChannelDetails { inner: ObjOps::heap_alloc(nativeChannelDetails { + channel_id: ::lightning::ln::ChannelId(channel_id_arg.data), counterparty: *unsafe { Box::from_raw(counterparty_arg.take_inner()) }, funding_txo: local_funding_txo_arg, + channel_type: local_channel_type_arg, short_channel_id: local_short_channel_id_arg, + outbound_scid_alias: local_outbound_scid_alias_arg, + inbound_scid_alias: local_inbound_scid_alias_arg, channel_value_satoshis: channel_value_satoshis_arg, unspendable_punishment_reserve: local_unspendable_punishment_reserve_arg, - user_id: user_id_arg, + user_channel_id: user_channel_id_arg.into(), + feerate_sat_per_1000_weight: local_feerate_sat_per_1000_weight_arg, + balance_msat: balance_msat_arg, outbound_capacity_msat: outbound_capacity_msat_arg, + next_outbound_htlc_limit_msat: next_outbound_htlc_limit_msat_arg, + next_outbound_htlc_minimum_msat: next_outbound_htlc_minimum_msat_arg, inbound_capacity_msat: inbound_capacity_msat_arg, confirmations_required: local_confirmations_required_arg, + confirmations: local_confirmations_arg, force_close_spend_delay: local_force_close_spend_delay_arg, is_outbound: is_outbound_arg, - is_funding_locked: is_funding_locked_arg, + is_channel_ready: is_channel_ready_arg, + channel_shutdown_state: local_channel_shutdown_state_arg, is_usable: is_usable_arg, is_public: is_public_arg, - })), is_owned: true } + inbound_htlc_minimum_msat: local_inbound_htlc_minimum_msat_arg, + inbound_htlc_maximum_msat: local_inbound_htlc_maximum_msat_arg, + config: local_config_arg, + }), is_owned: true } } impl Clone for ChannelDetails { fn clone(&self) -> Self { Self { - inner: if <*mut nativeChannelDetails>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativeChannelDetails>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -718,277 +2153,640 @@ impl Clone for ChannelDetails { #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method pub(crate) extern "C" fn ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelDetails)).clone() })) as *mut c_void } #[no_mangle] /// Creates a copy of the ChannelDetails pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails { orig.clone() } -/// If a payment fails to send, it can be in one of several states. This enum is returned as the -/// Err() type describing which state the payment is in, see the description of individual enum -/// states for more. +/// Get a string which allows debug introspection of a ChannelDetails object +pub extern "C" fn ChannelDetails_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::ChannelDetails }).into()} +/// Gets the current SCID which should be used to identify this channel for inbound payments. +/// This should be used for providing invoice hints or in any other context where our +/// counterparty will forward a payment to us. +/// +/// This is either the [`ChannelDetails::inbound_scid_alias`], if set, or the +/// [`ChannelDetails::short_channel_id`]. See those for more information. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelDetails_get_inbound_payment_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_inbound_payment_scid(); + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { ret.unwrap() }) }; + local_ret +} + +/// Gets the current SCID which should be used to identify this channel for outbound payments. +/// This should be used in [`Route`]s to describe the first hop or in other contexts where +/// we're sending or forwarding a payment outbound over this channel. +/// +/// This is either the [`ChannelDetails::short_channel_id`], if set, or the +/// [`ChannelDetails::outbound_scid_alias`]. See those for more information. #[must_use] +#[no_mangle] +pub extern "C" fn ChannelDetails_get_outbound_payment_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelDetails) -> crate::c_types::derived::COption_u64Z { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_outbound_payment_scid(); + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { ret.unwrap() }) }; + local_ret +} + +/// Further information on the details of the channel shutdown. +/// Upon channels being forced closed (i.e. commitment transaction confirmation detected +/// by `ChainMonitor`), ChannelShutdownState will be set to `ShutdownComplete` or +/// the channel will be removed shortly. +/// Also note, that in normal operation, peers could disconnect at any of these states +/// and require peer re-connection before making progress onto other states #[derive(Clone)] +#[must_use] #[repr(C)] -pub enum PaymentSendFailure { - /// A parameter which was passed to send_payment was invalid, preventing us from attempting to - /// send the payment at all. No channel state has been changed or messages sent to peers, and - /// once you've changed the parameter at error, you can freely retry the payment in full. - ParameterError(crate::lightning::util::errors::APIError), - /// A parameter in a single path which was passed to send_payment was invalid, preventing us - /// from attempting to send the payment at all. No channel state has been changed or messages - /// sent to peers, and once you've changed the parameter at error, you can freely retry the - /// payment in full. - /// - /// The results here are ordered the same as the paths in the route object which was passed to - /// send_payment. - PathParameterError(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ), - /// All paths which were attempted failed to send, with no channel state change taking place. - /// You can freely retry the payment in full (though you probably want to do so over different - /// paths than the ones selected). - AllFailedRetrySafe(crate::c_types::derived::CVec_APIErrorZ), - /// Some paths which were attempted failed to send, though possibly not all. At least some - /// paths have irrevocably committed to the HTLC and retrying the payment in full would result - /// in over-/re-payment. - /// - /// The results here are ordered the same as the paths in the route object which was passed to - /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely - /// retried (though there is currently no API with which to do so). - /// - /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried - /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the - /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel - /// with the latest update_id. - PartialFailure(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ), -} -use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailure; -impl PaymentSendFailure { +pub enum ChannelShutdownState { + /// Channel has not sent or received a shutdown message. + NotShuttingDown, + /// Local node has sent a shutdown message for this channel. + ShutdownInitiated, + /// Shutdown message exchanges have concluded and the channels are in the midst of + /// resolving all existing open HTLCs before closing can continue. + ResolvingHTLCs, + /// All HTLCs have been resolved, nodes are currently negotiating channel close onchain fee rates. + NegotiatingClosingFee, + /// We've successfully negotiated a closing_signed dance. At this point `ChannelManager` is about + /// to drop the channel. + ShutdownComplete, +} +use lightning::ln::channelmanager::ChannelShutdownState as ChannelShutdownStateImport; +pub(crate) type nativeChannelShutdownState = ChannelShutdownStateImport; + +impl ChannelShutdownState { #[allow(unused)] - pub(crate) fn to_native(&self) -> nativePaymentSendFailure { + pub(crate) fn to_native(&self) -> nativeChannelShutdownState { match self { - PaymentSendFailure::ParameterError (ref a, ) => { - let mut a_nonref = (*a).clone(); - nativePaymentSendFailure::ParameterError ( - a_nonref.into_native(), - ) - }, - PaymentSendFailure::PathParameterError (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); }; - nativePaymentSendFailure::PathParameterError ( - local_a_nonref, - ) + ChannelShutdownState::NotShuttingDown => nativeChannelShutdownState::NotShuttingDown, + ChannelShutdownState::ShutdownInitiated => nativeChannelShutdownState::ShutdownInitiated, + ChannelShutdownState::ResolvingHTLCs => nativeChannelShutdownState::ResolvingHTLCs, + ChannelShutdownState::NegotiatingClosingFee => nativeChannelShutdownState::NegotiatingClosingFee, + ChannelShutdownState::ShutdownComplete => nativeChannelShutdownState::ShutdownComplete, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeChannelShutdownState { + match self { + ChannelShutdownState::NotShuttingDown => nativeChannelShutdownState::NotShuttingDown, + ChannelShutdownState::ShutdownInitiated => nativeChannelShutdownState::ShutdownInitiated, + ChannelShutdownState::ResolvingHTLCs => nativeChannelShutdownState::ResolvingHTLCs, + ChannelShutdownState::NegotiatingClosingFee => nativeChannelShutdownState::NegotiatingClosingFee, + ChannelShutdownState::ShutdownComplete => nativeChannelShutdownState::ShutdownComplete, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &ChannelShutdownStateImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeChannelShutdownState) }; + match native { + nativeChannelShutdownState::NotShuttingDown => ChannelShutdownState::NotShuttingDown, + nativeChannelShutdownState::ShutdownInitiated => ChannelShutdownState::ShutdownInitiated, + nativeChannelShutdownState::ResolvingHTLCs => ChannelShutdownState::ResolvingHTLCs, + nativeChannelShutdownState::NegotiatingClosingFee => ChannelShutdownState::NegotiatingClosingFee, + nativeChannelShutdownState::ShutdownComplete => ChannelShutdownState::ShutdownComplete, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeChannelShutdownState) -> Self { + match native { + nativeChannelShutdownState::NotShuttingDown => ChannelShutdownState::NotShuttingDown, + nativeChannelShutdownState::ShutdownInitiated => ChannelShutdownState::ShutdownInitiated, + nativeChannelShutdownState::ResolvingHTLCs => ChannelShutdownState::ResolvingHTLCs, + nativeChannelShutdownState::NegotiatingClosingFee => ChannelShutdownState::NegotiatingClosingFee, + nativeChannelShutdownState::ShutdownComplete => ChannelShutdownState::ShutdownComplete, + } + } +} +/// Creates a copy of the ChannelShutdownState +#[no_mangle] +pub extern "C" fn ChannelShutdownState_clone(orig: &ChannelShutdownState) -> ChannelShutdownState { + orig.clone() +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ChannelShutdownState_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const ChannelShutdownState)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn ChannelShutdownState_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut ChannelShutdownState) }; +} +#[no_mangle] +/// Utility method to constructs a new NotShuttingDown-variant ChannelShutdownState +pub extern "C" fn ChannelShutdownState_not_shutting_down() -> ChannelShutdownState { + ChannelShutdownState::NotShuttingDown} +#[no_mangle] +/// Utility method to constructs a new ShutdownInitiated-variant ChannelShutdownState +pub extern "C" fn ChannelShutdownState_shutdown_initiated() -> ChannelShutdownState { + ChannelShutdownState::ShutdownInitiated} +#[no_mangle] +/// Utility method to constructs a new ResolvingHTLCs-variant ChannelShutdownState +pub extern "C" fn ChannelShutdownState_resolving_htlcs() -> ChannelShutdownState { + ChannelShutdownState::ResolvingHTLCs} +#[no_mangle] +/// Utility method to constructs a new NegotiatingClosingFee-variant ChannelShutdownState +pub extern "C" fn ChannelShutdownState_negotiating_closing_fee() -> ChannelShutdownState { + ChannelShutdownState::NegotiatingClosingFee} +#[no_mangle] +/// Utility method to constructs a new ShutdownComplete-variant ChannelShutdownState +pub extern "C" fn ChannelShutdownState_shutdown_complete() -> ChannelShutdownState { + ChannelShutdownState::ShutdownComplete} +/// Get a string which allows debug introspection of a ChannelShutdownState object +pub extern "C" fn ChannelShutdownState_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::ChannelShutdownState }).into()} +/// Checks if two ChannelShutdownStates contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn ChannelShutdownState_eq(a: &ChannelShutdownState, b: &ChannelShutdownState) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} +/// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments. +/// These include payments that have yet to find a successful path, or have unresolved HTLCs. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum RecentPaymentDetails { + /// When an invoice was requested and thus a payment has not yet been sent. + AwaitingInvoice { + /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify + /// a payment and ensure idempotency in LDK. + payment_id: crate::c_types::ThirtyTwoBytes, + }, + /// When a payment is still being sent and awaiting successful delivery. + Pending { + /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify + /// a payment and ensure idempotency in LDK. + payment_id: crate::c_types::ThirtyTwoBytes, + /// Hash of the payment that is currently being sent but has yet to be fulfilled or + /// abandoned. + payment_hash: crate::c_types::ThirtyTwoBytes, + /// Total amount (in msat, excluding fees) across all paths for this payment, + /// not just the amount currently inflight. + total_msat: u64, + }, + /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have + /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the + /// payment is removed from tracking. + Fulfilled { + /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify + /// a payment and ensure idempotency in LDK. + payment_id: crate::c_types::ThirtyTwoBytes, + /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`] + /// made before LDK version 0.0.104. + payment_hash: crate::c_types::derived::COption_ThirtyTwoBytesZ, + }, + /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly + /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all + /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated. + Abandoned { + /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify + /// a payment and ensure idempotency in LDK. + payment_id: crate::c_types::ThirtyTwoBytes, + /// Hash of the payment that we have given up trying to send. + payment_hash: crate::c_types::ThirtyTwoBytes, + }, +} +use lightning::ln::channelmanager::RecentPaymentDetails as RecentPaymentDetailsImport; +pub(crate) type nativeRecentPaymentDetails = RecentPaymentDetailsImport; + +impl RecentPaymentDetails { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeRecentPaymentDetails { + match self { + RecentPaymentDetails::AwaitingInvoice {ref payment_id, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + nativeRecentPaymentDetails::AwaitingInvoice { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + } }, - PaymentSendFailure::AllFailedRetrySafe (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); }; - nativePaymentSendFailure::AllFailedRetrySafe ( - local_a_nonref, - ) + RecentPaymentDetails::Pending {ref payment_id, ref payment_hash, ref total_msat, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut total_msat_nonref = Clone::clone(total_msat); + nativeRecentPaymentDetails::Pending { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), + total_msat: total_msat_nonref, + } }, - PaymentSendFailure::PartialFailure (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); }; - nativePaymentSendFailure::PartialFailure ( - local_a_nonref, - ) + RecentPaymentDetails::Fulfilled {ref payment_id, ref payment_hash, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut local_payment_hash_nonref = { /*payment_hash_nonref*/ let payment_hash_nonref_opt = payment_hash_nonref; if payment_hash_nonref_opt.is_none() { None } else { Some({ { ::lightning::ln::PaymentHash({ payment_hash_nonref_opt.take() }.data) }})} }; + nativeRecentPaymentDetails::Fulfilled { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + payment_hash: local_payment_hash_nonref, + } + }, + RecentPaymentDetails::Abandoned {ref payment_id, ref payment_hash, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + nativeRecentPaymentDetails::Abandoned { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), + } }, } } #[allow(unused)] - pub(crate) fn into_native(self) -> nativePaymentSendFailure { + pub(crate) fn into_native(self) -> nativeRecentPaymentDetails { match self { - PaymentSendFailure::ParameterError (mut a, ) => { - nativePaymentSendFailure::ParameterError ( - a.into_native(), - ) + RecentPaymentDetails::AwaitingInvoice {mut payment_id, } => { + nativeRecentPaymentDetails::AwaitingInvoice { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + } }, - PaymentSendFailure::PathParameterError (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); }; - nativePaymentSendFailure::PathParameterError ( - local_a, - ) + RecentPaymentDetails::Pending {mut payment_id, mut payment_hash, mut total_msat, } => { + nativeRecentPaymentDetails::Pending { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), + total_msat: total_msat, + } }, - PaymentSendFailure::AllFailedRetrySafe (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); }; - nativePaymentSendFailure::AllFailedRetrySafe ( - local_a, - ) + RecentPaymentDetails::Fulfilled {mut payment_id, mut payment_hash, } => { + let mut local_payment_hash = { /*payment_hash*/ let payment_hash_opt = payment_hash; if payment_hash_opt.is_none() { None } else { Some({ { ::lightning::ln::PaymentHash({ payment_hash_opt.take() }.data) }})} }; + nativeRecentPaymentDetails::Fulfilled { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + payment_hash: local_payment_hash, + } }, - PaymentSendFailure::PartialFailure (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); }; - nativePaymentSendFailure::PartialFailure ( - local_a, - ) + RecentPaymentDetails::Abandoned {mut payment_id, mut payment_hash, } => { + nativeRecentPaymentDetails::Abandoned { + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), + } }, } } #[allow(unused)] - pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self { + pub(crate) fn from_native(native: &RecentPaymentDetailsImport) -> Self { + let native = unsafe { &*(native as *const _ as *const c_void as *const nativeRecentPaymentDetails) }; match native { - nativePaymentSendFailure::ParameterError (ref a, ) => { - let mut a_nonref = (*a).clone(); - PaymentSendFailure::ParameterError ( - crate::lightning::util::errors::APIError::native_into(a_nonref), - ) + nativeRecentPaymentDetails::AwaitingInvoice {ref payment_id, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + RecentPaymentDetails::AwaitingInvoice { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + } }, - nativePaymentSendFailure::PathParameterError (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; - PaymentSendFailure::PathParameterError ( - local_a_nonref.into(), - ) + nativeRecentPaymentDetails::Pending {ref payment_id, ref payment_hash, ref total_msat, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut total_msat_nonref = Clone::clone(total_msat); + RecentPaymentDetails::Pending { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 }, + total_msat: total_msat_nonref, + } }, - nativePaymentSendFailure::AllFailedRetrySafe (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; - PaymentSendFailure::AllFailedRetrySafe ( - local_a_nonref.into(), - ) + nativeRecentPaymentDetails::Fulfilled {ref payment_id, ref payment_hash, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut local_payment_hash_nonref = if payment_hash_nonref.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.unwrap().0 } }) }; + RecentPaymentDetails::Fulfilled { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + payment_hash: local_payment_hash_nonref, + } }, - nativePaymentSendFailure::PartialFailure (ref a, ) => { - let mut a_nonref = (*a).clone(); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; - PaymentSendFailure::PartialFailure ( - local_a_nonref.into(), - ) + nativeRecentPaymentDetails::Abandoned {ref payment_id, ref payment_hash, } => { + let mut payment_id_nonref = Clone::clone(payment_id); + let mut payment_hash_nonref = Clone::clone(payment_hash); + RecentPaymentDetails::Abandoned { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 }, + } }, } } #[allow(unused)] - pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self { + pub(crate) fn native_into(native: nativeRecentPaymentDetails) -> Self { match native { - nativePaymentSendFailure::ParameterError (mut a, ) => { - PaymentSendFailure::ParameterError ( - crate::lightning::util::errors::APIError::native_into(a), - ) + nativeRecentPaymentDetails::AwaitingInvoice {mut payment_id, } => { + RecentPaymentDetails::AwaitingInvoice { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + } }, - nativePaymentSendFailure::PathParameterError (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; - PaymentSendFailure::PathParameterError ( - local_a.into(), - ) + nativeRecentPaymentDetails::Pending {mut payment_id, mut payment_hash, mut total_msat, } => { + RecentPaymentDetails::Pending { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, + total_msat: total_msat, + } }, - nativePaymentSendFailure::AllFailedRetrySafe (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; - PaymentSendFailure::AllFailedRetrySafe ( - local_a.into(), - ) + nativeRecentPaymentDetails::Fulfilled {mut payment_id, mut payment_hash, } => { + let mut local_payment_hash = if payment_hash.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: payment_hash.unwrap().0 } }) }; + RecentPaymentDetails::Fulfilled { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + payment_hash: local_payment_hash, + } }, - nativePaymentSendFailure::PartialFailure (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; - PaymentSendFailure::PartialFailure ( - local_a.into(), - ) + nativeRecentPaymentDetails::Abandoned {mut payment_id, mut payment_hash, } => { + RecentPaymentDetails::Abandoned { + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, + } }, } } } -/// Frees any resources used by the PaymentSendFailure +/// Frees any resources used by the RecentPaymentDetails #[no_mangle] -pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { } -/// Creates a copy of the PaymentSendFailure +pub extern "C" fn RecentPaymentDetails_free(this_ptr: RecentPaymentDetails) { } +/// Creates a copy of the RecentPaymentDetails #[no_mangle] -pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure { +pub extern "C" fn RecentPaymentDetails_clone(orig: &RecentPaymentDetails) -> RecentPaymentDetails { orig.clone() } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn RecentPaymentDetails_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const RecentPaymentDetails)).clone() })) as *mut c_void +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn RecentPaymentDetails_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut RecentPaymentDetails) }; +} +#[no_mangle] +/// Utility method to constructs a new AwaitingInvoice-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_awaiting_invoice(payment_id: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails { + RecentPaymentDetails::AwaitingInvoice { + payment_id, + } +} +#[no_mangle] +/// Utility method to constructs a new Pending-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_pending(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes, total_msat: u64) -> RecentPaymentDetails { + RecentPaymentDetails::Pending { + payment_id, + payment_hash, + total_msat, + } +} +#[no_mangle] +/// Utility method to constructs a new Fulfilled-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_fulfilled(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::derived::COption_ThirtyTwoBytesZ) -> RecentPaymentDetails { + RecentPaymentDetails::Fulfilled { + payment_id, + payment_hash, + } +} +#[no_mangle] +/// Utility method to constructs a new Abandoned-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_abandoned(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails { + RecentPaymentDetails::Abandoned { + payment_id, + payment_hash, + } +} +/// Get a string which allows debug introspection of a RecentPaymentDetails object +pub extern "C" fn RecentPaymentDetails_debug_str_void(o: *const c_void) -> Str { + alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::RecentPaymentDetails }).into()} + +use lightning::ln::channelmanager::PhantomRouteHints as nativePhantomRouteHintsImport; +pub(crate) type nativePhantomRouteHints = nativePhantomRouteHintsImport; + +/// Route hints used in constructing invoices for [phantom node payents]. +/// +/// [phantom node payments]: crate::sign::PhantomKeysManager +#[must_use] +#[repr(C)] +pub struct PhantomRouteHints { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativePhantomRouteHints, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for PhantomRouteHints { + fn drop(&mut self) { + if self.is_owned && !<*mut nativePhantomRouteHints>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the PhantomRouteHints, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn PhantomRouteHints_free(this_obj: PhantomRouteHints) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PhantomRouteHints_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativePhantomRouteHints) }; +} +#[allow(unused)] +impl PhantomRouteHints { + pub(crate) fn get_native_ref(&self) -> &'static nativePhantomRouteHints { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePhantomRouteHints { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativePhantomRouteHints { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +/// The list of channels to be included in the invoice route hints. +#[no_mangle] +pub extern "C" fn PhantomRouteHints_get_channels(this_ptr: &PhantomRouteHints) -> crate::c_types::derived::CVec_ChannelDetailsZ { + let mut inner_val = &mut this_ptr.get_native_mut_ref().channels; + let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.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_inner_val.into() +} +/// The list of channels to be included in the invoice route hints. +#[no_mangle] +pub extern "C" fn PhantomRouteHints_set_channels(this_ptr: &mut PhantomRouteHints, mut val: crate::c_types::derived::CVec_ChannelDetailsZ) { + let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channels = local_val; +} +/// A fake scid used for representing the phantom node's fake channel in generating the invoice +/// route hints. +#[no_mangle] +pub extern "C" fn PhantomRouteHints_get_phantom_scid(this_ptr: &PhantomRouteHints) -> u64 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().phantom_scid; + *inner_val +} +/// A fake scid used for representing the phantom node's fake channel in generating the invoice +/// route hints. +#[no_mangle] +pub extern "C" fn PhantomRouteHints_set_phantom_scid(this_ptr: &mut PhantomRouteHints, mut val: u64) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.phantom_scid = val; +} +/// The pubkey of the real backing node that would ultimately receive the payment. #[no_mangle] -/// Utility method to constructs a new ParameterError-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_parameter_error(a: crate::lightning::util::errors::APIError) -> PaymentSendFailure { - PaymentSendFailure::ParameterError(a, ) +pub extern "C" fn PhantomRouteHints_get_real_node_pubkey(this_ptr: &PhantomRouteHints) -> crate::c_types::PublicKey { + let mut inner_val = &mut this_ptr.get_native_mut_ref().real_node_pubkey; + crate::c_types::PublicKey::from_rust(&inner_val) } +/// The pubkey of the real backing node that would ultimately receive the payment. #[no_mangle] -/// Utility method to constructs a new PathParameterError-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_path_parameter_error(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure { - PaymentSendFailure::PathParameterError(a, ) +pub extern "C" fn PhantomRouteHints_set_real_node_pubkey(this_ptr: &mut PhantomRouteHints, mut val: crate::c_types::PublicKey) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.real_node_pubkey = val.into_rust(); } +/// Constructs a new PhantomRouteHints given each field +#[must_use] #[no_mangle] -/// Utility method to constructs a new AllFailedRetrySafe-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_all_failed_retry_safe(a: crate::c_types::derived::CVec_APIErrorZ) -> PaymentSendFailure { - PaymentSendFailure::AllFailedRetrySafe(a, ) +pub extern "C" fn PhantomRouteHints_new(mut channels_arg: crate::c_types::derived::CVec_ChannelDetailsZ, mut phantom_scid_arg: u64, mut real_node_pubkey_arg: crate::c_types::PublicKey) -> PhantomRouteHints { + let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; + PhantomRouteHints { inner: ObjOps::heap_alloc(nativePhantomRouteHints { + channels: local_channels_arg, + phantom_scid: phantom_scid_arg, + real_node_pubkey: real_node_pubkey_arg.into_rust(), + }), is_owned: true } +} +impl Clone for PhantomRouteHints { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativePhantomRouteHints>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn PhantomRouteHints_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativePhantomRouteHints)).clone() })) as *mut c_void } #[no_mangle] -/// Utility method to constructs a new PartialFailure-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_partial_failure(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure { - PaymentSendFailure::PartialFailure(a, ) +/// Creates a copy of the PhantomRouteHints +pub extern "C" fn PhantomRouteHints_clone(orig: &PhantomRouteHints) -> PhantomRouteHints { + orig.clone() } -/// Constructs a new ChannelManager to hold several channels and route between them. +/// Constructs a new `ChannelManager` to hold several channels and route between them. +/// +/// The current time or latest block header time can be provided as the `current_timestamp`. /// /// This is the main \"logic hub\" for all channel-related actions, and implements -/// ChannelMessageHandler. +/// [`ChannelMessageHandler`]. /// /// Non-proportional fees are fixed according to our risk using the provided fee estimator. /// -/// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`! +/// Users need to notify the new `ChannelManager` when a new block is connected or +/// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting +/// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for +/// more details. /// -/// Users need to notify the new ChannelManager when a new block is connected or -/// disconnected using its `block_connected` and `block_disconnected` methods, starting -/// from after `params.latest_hash`. +/// [`block_connected`]: chain::Listen::block_connected +/// [`block_disconnected`]: chain::Listen::block_disconnected +/// [`params.best_block.block_hash`]: chain::BestBlock::block_hash #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters) -> ChannelManager { - let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, logger, keys_manager, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) }); - ChannelManager { inner: Box::into_raw(Box::new(ret)), is_owned: true } +pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut entropy_source: crate::lightning::sign::EntropySource, mut node_signer: crate::lightning::sign::NodeSigner, mut signer_provider: crate::lightning::sign::SignerProvider, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters, mut current_timestamp: u32) -> crate::lightning::ln::channelmanager::ChannelManager { + let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, router, logger, entropy_source, node_signer, signer_provider, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) }, current_timestamp); + crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Gets the current configuration applied to all new channels, as +/// Gets the current configuration applied to all new channels. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &ChannelManager) -> crate::lightning::util::config::UserConfig { - let mut ret = unsafe { &*this_arg.inner }.get_current_default_configuration(); - crate::lightning::util::config::UserConfig { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } +pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::util::config::UserConfig { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_current_default_configuration(); + crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::util::config::UserConfig<>) as *mut _) }, is_owned: false } } /// Creates a new outbound channel to the given remote node and with the given value. /// -/// user_id will be provided back as user_channel_id in FundingGenerationReady events to allow -/// tracking of which events correspond with which create_channel call. Note that the -/// user_channel_id defaults to 0 for inbound channels, so you may wish to avoid using 0 for -/// user_id here. user_id has no meaning inside of LDK, it is simply copied to events and -/// otherwise ignored. +/// `user_channel_id` will be provided back as in +/// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events +/// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a +/// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it +/// is simply copied to events and otherwise ignored. /// -/// If successful, will generate a SendOpenChannel message event, so you should probably poll -/// PeerManager::process_events afterwards. +/// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is +/// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`. /// -/// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is -/// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000. +/// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to +/// generate a shutdown scriptpubkey or destination script set by +/// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`]. /// /// Note that we do not check if you are currently connected to the given peer. If no /// connection is available, the outbound `open_channel` message may fail to send, resulting in -/// the channel eventually being silently forgotten. +/// the channel eventually being silently forgotten (dropped on reload). +/// +/// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the +/// channel. Otherwise, a random one will be generated for you. +/// +/// Returns the new Channel's temporary `channel_id`. This ID will appear as +/// [`Event::FundingGenerationReady::temporary_channel_id`] and in +/// [`ChannelDetails::channel_id`] until after +/// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for +/// one derived from the funding transaction's TXID. If the counterparty rejects the channel +/// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`]. +/// +/// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id +/// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id +/// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id /// /// Note that override_config (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_id: u64, mut override_config: crate::lightning::util::config::UserConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ { +pub extern "C" fn ChannelManager_create_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_channel_id: crate::c_types::U128, mut temporary_channel_id: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut override_config: crate::lightning::util::config::UserConfig) -> crate::c_types::derived::CResult_ThirtyTwoBytesAPIErrorZ { + let mut local_temporary_channel_id = { /*temporary_channel_id*/ let temporary_channel_id_opt = temporary_channel_id; if temporary_channel_id_opt.is_none() { None } else { Some({ { ::lightning::ln::ChannelId({ temporary_channel_id_opt.take() }.data) }})} }; let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) }; - let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_channel_id.into(), local_temporary_channel_id, local_override_config); + 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::util::errors::APIError::native_into(e) }).into() }; local_ret } -/// Gets the list of open channels, in random order. See ChannelDetail field documentation for +/// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for /// more information. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ { - let mut ret = unsafe { &*this_arg.inner }.list_channels(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); }; +pub extern "C" fn ChannelManager_list_channels(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_channels(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; local_ret.into() } /// Gets the list of usable channels, in random order. Useful as an argument to -/// get_route to ensure non-announced channels are used. +/// [`Router::find_route`] to ensure non-announced channels are used. /// /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria /// are. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ { - let mut ret = unsafe { &*this_arg.inner }.list_usable_channels(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); }; +pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_usable_channels(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; + local_ret.into() +} + +/// Gets the list of channels we have with a given counterparty, in random order. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_list_channels_with_counterparty(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CVec_ChannelDetailsZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_channels_with_counterparty(&counterparty_node_id.into_rust()); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; + local_ret.into() +} + +/// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a +/// successful path, or have unresolved HTLCs. +/// +/// This can be useful for payments that may have been prepared, but ultimately not sent, as a +/// result of a crash. If such a payment exists, is not listed here, and an +/// [`Event::PaymentSent`] has not been received, you may consider resending the payment. +/// +/// [`Event::PaymentSent`]: events::Event::PaymentSent +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_list_recent_payments(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_RecentPaymentDetailsZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_recent_payments(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::RecentPaymentDetails::native_into(item) }); }; local_ret.into() } @@ -996,21 +2794,96 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) /// will be accepted on the given channel, and after additional timeout/the closing of all /// pending HTLCs, the channel will be closed on chain. /// -/// May generate a SendShutdown message event on success, which should be relayed. +/// * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and +/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`] +/// fee estimate. +/// * If our counterparty is the channel initiator, we will require a channel closing +/// transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which +/// would appear on a force-closure transaction, whichever is lower. We will allow our +/// counterparty to pay as much fee as they'd like, however. +/// +/// May generate a [`SendShutdown`] message event on success, which should be relayed. +/// +/// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to +/// generate a shutdown scriptpubkey or destination script set by +/// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the +/// channel. +/// +/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis +/// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum +/// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee +/// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_close_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel(&::lightning::ln::ChannelId(unsafe { *channel_id }), &counterparty_node_id.into_rust()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs +/// will be accepted on the given channel, and after additional timeout/the closing of all +/// pending HTLCs, the channel will be closed on chain. +/// +/// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated +/// the channel being closed or not: +/// * If we are the channel initiator, we will pay at least this feerate on the closing +/// transaction. The upper-bound is set by +/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`] +/// fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater). +/// * If our counterparty is the channel initiator, we will refuse to accept a channel closure +/// transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which +/// will appear on a force-closure transaction, whichever is lower). +/// +/// The `shutdown_script` provided will be used as the `scriptPubKey` for the closing transaction. +/// Will fail if a shutdown script has already been set for this channel by +/// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must +/// also be compatible with our and the counterparty's features. +/// +/// May generate a [`SendShutdown`] message event on success, which should be relayed. +/// +/// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to +/// generate a shutdown scriptpubkey or destination script set by +/// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the +/// channel. +/// +/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis +/// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee +/// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown +/// +/// Note that shutdown_script (or a relevant inner pointer) may be NULL or all-0s to represent None +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_close_channel_with_feerate_and_script(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey, mut target_feerate_sats_per_1000_weight: crate::c_types::derived::COption_u32Z, mut shutdown_script: crate::lightning::ln::script::ShutdownScript) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut local_target_feerate_sats_per_1000_weight = if target_feerate_sats_per_1000_weight.is_some() { Some( { target_feerate_sats_per_1000_weight.take() }) } else { None }; + let mut local_shutdown_script = if shutdown_script.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(shutdown_script.take_inner()) } }) }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel_with_feerate_and_script(&::lightning::ln::ChannelId(unsafe { *channel_id }), &counterparty_node_id.into_rust(), local_target_feerate_sats_per_1000_weight, local_shutdown_script); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Force closes a channel, immediately broadcasting the latest local transaction(s) and +/// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to +/// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding +/// channel. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ { - let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id}); +pub extern "C" fn ChannelManager_force_close_broadcasting_latest_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_broadcasting_latest_txn(&::lightning::ln::ChannelId(unsafe { *channel_id }), &counterparty_node_id.into_rust()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } -/// Force closes a channel, immediately broadcasting the latest local commitment transaction to -/// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager. +/// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting +/// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the +/// `counterparty_node_id` isn't the counterparty of the corresponding channel. +/// +/// You can always get the latest local transaction(s) to broadcast from +/// [`ChannelMonitor::get_latest_holder_commitment_txn`]. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ { - let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id}); +pub extern "C" fn ChannelManager_force_close_without_broadcasting_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_without_broadcasting_txn(&::lightning::ln::ChannelId(unsafe { *channel_id }), &counterparty_node_id.into_rust()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -1018,78 +2891,200 @@ pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, /// Force close all channels, immediately broadcasting the latest local commitment transaction /// for each to the chain and rejecting new HTLCs on each. #[no_mangle] -pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.force_close_all_channels() +pub extern "C" fn ChannelManager_force_close_all_channels_broadcasting_latest_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels_broadcasting_latest_txn() +} + +/// Force close all channels rejecting new HTLCs on each but without broadcasting the latest +/// local transaction(s). +#[no_mangle] +pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels_without_broadcasting_txn() } /// Sends a payment along a given route. /// -/// Value parameters are provided via the last hop in route, see documentation for RouteHop +/// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`] /// fields for more info. /// -/// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative -/// payment), we don't do anything to stop you! We always try to ensure that if the provided -/// next hop knows the preimage to payment_hash they can claim an additional amount as -/// specified in the last hop in the route! Thus, you should probably do your own -/// payment_preimage tracking (which you should already be doing as they represent \"proof of -/// payment\") and prevent double-sends yourself. +/// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via +/// [`PeerManager::process_events`]). +/// +/// # Avoiding Duplicate Payments +/// +/// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this +/// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment +/// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an +/// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a +/// second payment with the same [`PaymentId`]. +/// +/// Thus, in order to ensure duplicate payments are not sent, you should implement your own +/// tracking of payments, including state to indicate once a payment has completed. Because you +/// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should +/// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the +/// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes. /// -/// May generate SendHTLCs message(s) event on success, which should be relayed. +/// Additionally, in the scenario where we begin the process of sending a payment, but crash +/// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're +/// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See +/// [`ChannelManager::list_recent_payments`] for more information. /// -/// Each path may have a different return value, and PaymentSendValue may return a Vec with +/// # Possible Error States on [`PaymentSendFailure`] +/// +/// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with /// each entry matching the corresponding-index entry in the route paths, see -/// PaymentSendFailure for more info. +/// [`PaymentSendFailure`] for more info. /// /// In general, a path may raise: -/// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee, +/// * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee, /// node public key) is specified. -/// * APIError::ChannelUnavailable if the next-hop channel is not available for updates -/// (including due to previous monitor update failure or new permanent monitor update -/// failure). -/// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the +/// * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been +/// closed, doesn't exist, or the peer is currently disconnected. +/// * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the /// relevant updates. /// -/// Note that depending on the type of the PaymentSendFailure the HTLC may have been +/// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a /// different route unless you intend to pay twice! /// -/// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate -/// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For -/// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route -/// must not contain multiple paths as multi-path payments require a recipient-provided -/// payment_secret. -/// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature -/// bit set (either as required or as available). If multiple paths are present in the Route, -/// we assume the invoice had the basic_mpp feature set. -/// -/// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None +/// [`RouteHop`]: crate::routing::router::RouteHop +/// [`Event::PaymentSent`]: events::Event::PaymentSent +/// [`Event::PaymentFailed`]: events::Event::PaymentFailed +/// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs +/// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events +/// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_payment_with_route(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment_with_route(route.get_native_ref(), ::lightning::ln::PaymentHash(payment_hash.data), *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on +/// `route_params` and retry failed payment paths based on `retry_strategy`. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { - let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) }; - let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; +pub extern "C" fn ChannelManager_send_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_NoneRetryableSendFailureZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment(::lightning::ln::PaymentHash(payment_hash.data), *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() }; local_ret } +/// Signals that no further attempts for the given payment should occur. Useful if you have a +/// pending outbound payment with retries remaining, but wish to stop retrying the payment before +/// retries are exhausted. +/// +/// # Event Generation +/// +/// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon +/// as there are no remaining pending HTLCs for this payment. +/// +/// Note that calling this method does *not* prevent a payment from succeeding. You must still +/// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to +/// determine the ultimate status of a payment. +/// +/// # Requested Invoices +/// +/// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning +/// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`] +/// and prevent any attempts at paying it once received. The other events may only be generated +/// once the invoice has been received. +/// +/// # Restart Behavior +/// +/// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the +/// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for +/// [`Event::InvoiceRequestFailed`]. +/// +/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice +#[no_mangle] +pub extern "C" fn ChannelManager_abandon_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_id: crate::c_types::ThirtyTwoBytes) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.abandon_payment(::lightning::ln::channelmanager::PaymentId(payment_id.data)) +} + /// Send a spontaneous payment, which is a payment that does not require the recipient to have /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify /// the preimage, it must be a cryptographically secure random value that no intermediate node /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will /// never reach the recipient. /// +/// See [`send_payment`] documentation for more details on the return value of this function +/// and idempotency guarantees provided by the [`PaymentId`] key. +/// /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See /// [`send_payment`] for more information about the risks of duplicate preimage usage. /// /// [`send_payment`]: Self::send_payment +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_ThirtyTwoBytesPaymentSendFailureZ { + let mut local_payment_preimage = { /*payment_preimage*/ let payment_preimage_opt = payment_preimage; if payment_preimage_opt.is_none() { None } else { Some({ { ::lightning::ln::PaymentPreimage({ payment_preimage_opt.take() }.data) }})} }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment(route.get_native_ref(), local_payment_preimage, *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); + 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::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route +/// based on `route_params` and retry failed payment paths based on `retry_strategy`. /// -/// Note that payment_preimage (or a relevant inner pointer) may be NULL or all-0s to represent None +/// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous +/// payments. +/// +/// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_spontaneous_payment_with_retry(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_ThirtyTwoBytesRetryableSendFailureZ { + let mut local_payment_preimage = { /*payment_preimage*/ let payment_preimage_opt = payment_preimage; if payment_preimage_opt.is_none() { None } else { Some({ { ::lightning::ln::PaymentPreimage({ payment_preimage_opt.take() }.data) }})} }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment_with_retry(local_payment_preimage, *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native()); + 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::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Send a payment that is probing the given route for liquidity. We calculate the +/// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows +/// us to easily discern them from real payments. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_probe(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut path: crate::lightning::routing::router::Path) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZPaymentSendFailureZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_probe(*unsafe { Box::from_raw(path.take_inner()) }); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Sends payment probes over all paths of a route that would be used to pay the given +/// amount to the given `node_id`. +/// +/// See [`ChannelManager::send_preflight_probes`] for more information. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_spontaneous_preflight_probes(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut node_id: crate::c_types::PublicKey, mut amount_msat: u64, mut final_cltv_expiry_delta: u32, mut liquidity_limit_multiplier: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZZProbeSendFailureZ { + let mut local_liquidity_limit_multiplier = if liquidity_limit_multiplier.is_some() { Some( { liquidity_limit_multiplier.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_preflight_probes(node_id.into_rust(), amount_msat, final_cltv_expiry_delta, local_liquidity_limit_multiplier); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_1.0 }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::ProbeSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Sends payment probes over all paths of a route that would be used to pay a route found +/// according to the given [`RouteParameters`]. +/// +/// This may be used to send \"pre-flight\" probes, i.e., to train our scorer before conducting +/// the actual payment. Note this is only useful if there likely is sufficient time for the +/// probe to settle before sending out the actual payment, e.g., when waiting for user +/// confirmation in a wallet UI. +/// +/// Otherwise, there is a chance the probe could take up some liquidity needed to complete the +/// actual payment. Users should therefore be cautious and might avoid sending probes if +/// liquidity is scarce and/or they don't expect the probe to return before they send the +/// payment. To mitigate this issue, channels with available liquidity less than the required +/// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight +/// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentHashPaymentSendFailureZ { - let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) }; - let mut ret = unsafe { &*this_arg.inner }.send_spontaneous_payment(unsafe { &*route.inner }, local_payment_preimage); - 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::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; +pub extern "C" fn ChannelManager_send_preflight_probes(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut route_params: crate::lightning::routing::router::RouteParameters, mut liquidity_limit_multiplier: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZZProbeSendFailureZ { + let mut local_liquidity_limit_multiplier = if liquidity_limit_multiplier.is_some() { Some( { liquidity_limit_multiplier.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_preflight_probes(*unsafe { Box::from_raw(route_params.take_inner()) }, local_liquidity_limit_multiplier); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_1.0 }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::ProbeSendFailure::native_into(e) }).into() }; local_ret } @@ -1098,7 +3093,11 @@ pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelMana /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`]. /// -/// Panics if a funding transaction has already been provided for this channel. +/// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation +/// across the p2p network. +/// +/// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided +/// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`]. /// /// May panic if the output found in the funding transaction is duplicative with some other /// channel (note that this should be trivially prevented by using unique funding transaction @@ -1112,169 +3111,460 @@ pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelMana /// not currently support replacing a funding transaction on an existing channel. Instead, /// create a new channel with a conflicting funding transaction. /// -/// [`Event::FundingGenerationReady`]: crate::util::events::Event::FundingGenerationReady -#[must_use] +/// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend +/// the wallet software generating the funding transaction to apply anti-fee sniping as +/// implemented by Bitcoin Core wallet. See +/// for more details. +/// +/// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady +/// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey, mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_transaction_generated(&::lightning::ln::ChannelId(unsafe { *temporary_channel_id }), &counterparty_node_id.into_rust(), funding_transaction.into_bitcoin()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Call this upon creation of a batch funding transaction for the given channels. +/// +/// Return values are identical to [`Self::funding_transaction_generated`], respective to +/// each individual channel and transaction output. +/// +/// Do NOT broadcast the funding transaction yourself. This batch funding transaction +/// will only be broadcast when we have safely received and persisted the counterparty's +/// signature for each channel. +/// +/// If there is an error, all channels in the batch are to be considered closed. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_batch_funding_transaction_generated(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut temporary_channels: crate::c_types::derived::CVec_C2Tuple_ThirtyTwoBytesPublicKeyZZ, mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut local_temporary_channels = Vec::new(); for mut item in temporary_channels.into_rust().drain(..) { local_temporary_channels.push( { let (mut orig_temporary_channels_0_0, mut orig_temporary_channels_0_1) = item.to_rust(); let mut local_temporary_channels_0 = (::lightning::ln::ChannelId(orig_temporary_channels_0_0.data), orig_temporary_channels_0_1.into_rust()); local_temporary_channels_0 }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.batch_funding_transaction_generated(&local_temporary_channels.iter().map(|(a, b)| (a, b)).collect::>()[..], funding_transaction.into_bitcoin()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Atomically applies partial updates to the [`ChannelConfig`] of the given channels. +/// +/// Once the updates are applied, each eligible channel (advertised with a known short channel +/// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`], +/// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated +/// containing the new [`ChannelUpdate`] message which should be broadcast to the network. +/// +/// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect +/// `counterparty_node_id` is provided. +/// +/// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value +/// below [`MIN_CLTV_EXPIRY_DELTA`]. +/// +/// If an error is returned, none of the updates should be considered applied. +/// +/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths +/// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat +/// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta +/// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate +/// [`ChannelUpdate`]: msgs::ChannelUpdate +/// [`ChannelUnavailable`]: APIError::ChannelUnavailable +/// [`APIMisuseError`]: APIError::APIMisuseError +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_update_partial_channel_config(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey, mut channel_ids: crate::c_types::derived::CVec_ThirtyTwoBytesZ, config_update: &crate::lightning::util::config::ChannelConfigUpdate) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut local_channel_ids = Vec::new(); for mut item in channel_ids.into_rust().drain(..) { local_channel_ids.push( { ::lightning::ln::ChannelId(item.data) }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_partial_channel_config(&counterparty_node_id.into_rust(), local_channel_ids, config_update.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Atomically updates the [`ChannelConfig`] for the given channels. +/// +/// Once the updates are applied, each eligible channel (advertised with a known short channel +/// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`], +/// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated +/// containing the new [`ChannelUpdate`] message which should be broadcast to the network. +/// +/// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect +/// `counterparty_node_id` is provided. +/// +/// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value +/// below [`MIN_CLTV_EXPIRY_DELTA`]. +/// +/// If an error is returned, none of the updates should be considered applied. +/// +/// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths +/// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat +/// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta +/// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate +/// [`ChannelUpdate`]: msgs::ChannelUpdate +/// [`ChannelUnavailable`]: APIError::ChannelUnavailable +/// [`APIMisuseError`]: APIError::APIMisuseError +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_update_channel_config(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey, mut channel_ids: crate::c_types::derived::CVec_ThirtyTwoBytesZ, config: &crate::lightning::util::config::ChannelConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut local_channel_ids = Vec::new(); for mut item in channel_ids.into_rust().drain(..) { local_channel_ids.push( { ::lightning::ln::ChannelId(item.data) }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_config(&counterparty_node_id.into_rust(), local_channel_ids, config.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Attempts to forward an intercepted HTLC over the provided channel id and with the provided +/// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event. +/// +/// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time +/// channel to a receiving node if the node lacks sufficient inbound liquidity. +/// +/// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use +/// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the +/// receiver's invoice route hints. These route hints will signal to LDK to generate an +/// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or +/// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event. +/// +/// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop +/// you from forwarding more than you received. See +/// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount +/// than expected. +/// +/// Errors if the event was not handled in time, in which case the HTLC was automatically failed +/// backwards. +/// +/// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs +/// [`HTLCIntercepted`]: events::Event::HTLCIntercepted +/// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_forward_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes, next_hop_channel_id: *const [u8; 32], mut next_node_id: crate::c_types::PublicKey, mut amt_to_forward_msat: u64) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.forward_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data), &::lightning::ln::ChannelId(unsafe { *next_hop_channel_id }), next_node_id.into_rust(), amt_to_forward_msat); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to +/// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`]. +/// +/// Errors if the event was not handled in time, in which case the HTLC was automatically failed +/// backwards. +/// +/// [`HTLCIntercepted`]: events::Event::HTLCIntercepted +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_fail_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data)); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret +} + +/// Processes HTLCs which are pending waiting on random forward delay. +/// +/// Should only really ever be called in response to a PendingHTLCsForwardable event. +/// Will likely generate further events. +#[no_mangle] +pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_pending_htlc_forwards() +} + +/// Performs actions which should happen on startup and roughly once per minute thereafter. +/// +/// This currently includes: +/// * Increasing or decreasing the on-chain feerate estimates for our outbound channels, +/// * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more +/// than a minute, informing the network that they should no longer attempt to route over +/// the channel. +/// * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs +/// with the current [`ChannelConfig`]. +/// * Removing peers which have disconnected but and no longer have any channels. +/// * Force-closing and removing channels which have not completed establishment in a timely manner. +/// * Forgetting about stale outbound payments, either those that have already been fulfilled +/// or those awaiting an invoice that hasn't been delivered in the necessary amount of time. +/// The latter is determined using the system clock in `std` and the highest seen block time +/// minus two hours in `no-std`. +/// +/// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate +/// estimate fetches. +/// +/// [`ChannelUpdate`]: msgs::ChannelUpdate +/// [`ChannelConfig`]: crate::util::config::ChannelConfig +#[no_mangle] +pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timer_tick_occurred() +} + +/// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect +/// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources +/// along the path (including in our own channel on which we received it). +/// +/// Note that in some cases around unclean shutdown, it is possible the payment may have +/// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a +/// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment +/// may have already been failed automatically by LDK if it was nearing its expiration time. +/// +/// While LDK will never claim a payment automatically on your behalf (i.e. without you calling +/// [`ChannelManager::claim_funds`]), you should still monitor for +/// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on +/// startup during which time claims that were in-progress at shutdown may be replayed. +#[no_mangle] +pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, payment_hash: *const [u8; 32]) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash })) +} + +/// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the +/// reason for the failure. +/// +/// See [`FailureCode`] for valid failure codes. #[no_mangle] -pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ { - let mut ret = unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, funding_transaction.into_bitcoin()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; - local_ret +pub extern "C" fn ChannelManager_fail_htlc_backwards_with_reason(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, payment_hash: *const [u8; 32], mut failure_code: crate::lightning::ln::channelmanager::FailureCode) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards_with_reason(&::lightning::ln::PaymentHash(unsafe { *payment_hash }), failure_code.into_native()) } -/// Regenerates channel_announcements and generates a signed node_announcement from the given -/// arguments, providing them in corresponding events via -/// [`get_and_clear_pending_msg_events`], if at least one public channel has been confirmed -/// on-chain. This effectively re-broadcasts all channel announcements and sends our node -/// announcement to ensure that the lightning P2P network is aware of the channels we have and -/// our network addresses. +/// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any +/// [`MessageSendEvent`]s needed to claim the payment. /// -/// `rgb` is a node \"color\" and `alias` is a printable human-readable string to describe this -/// node to humans. They carry no in-protocol meaning. +/// This method is guaranteed to ensure the payment has been claimed but only if the current +/// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race +/// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment +/// successful. It will generally be available in the next [`process_pending_events`] call. /// -/// `addresses` represent the set (possibly empty) of socket addresses on which this node -/// accepts incoming connections. These will be included in the node_announcement, publicly -/// tying these addresses together and to this node. If you wish to preserve user privacy, -/// addresses should likely contain only Tor Onion addresses. +/// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or +/// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable` +/// event matches your expectation. If you fail to do so and call this method, you may provide +/// the sender \"proof-of-payment\" when they did not fulfill the full expected payment. /// -/// Panics if `addresses` is absurdly large (more than 500). +/// This function will fail the payment if it has custom TLVs with even type numbers, as we +/// will assume they are unknown. If you intend to accept even custom TLVs, you should use +/// [`claim_funds_with_known_custom_tlvs`]. /// -/// [`get_and_clear_pending_msg_events`]: MessageSendEventsProvider::get_and_clear_pending_msg_events +/// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable +/// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline +/// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed +/// [`process_pending_events`]: EventsProvider::process_pending_events +/// [`create_inbound_payment`]: Self::create_inbound_payment +/// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash +/// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs #[no_mangle] -pub extern "C" fn ChannelManager_broadcast_node_announcement(this_arg: &ChannelManager, mut rgb: crate::c_types::ThreeBytes, mut alias: crate::c_types::ThirtyTwoBytes, mut addresses: crate::c_types::derived::CVec_NetAddressZ) { - let mut local_addresses = Vec::new(); for mut item in addresses.into_rust().drain(..) { local_addresses.push( { item.into_native() }); }; - unsafe { &*this_arg.inner }.broadcast_node_announcement(rgb.data, alias.data, local_addresses) +pub extern "C" fn ChannelManager_claim_funds(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data)) } -/// Processes HTLCs which are pending waiting on random forward delay. +/// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with +/// even type numbers. /// -/// Should only really ever be called in response to a PendingHTLCsForwardable event. -/// Will likely generate further events. +/// # Note +/// +/// You MUST check you've understood all even TLVs before using this to +/// claim, otherwise you may unintentionally agree to some protocol you do not understand. +/// +/// [`claim_funds`]: Self::claim_funds #[no_mangle] -pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.process_pending_htlc_forwards() +pub extern "C" fn ChannelManager_claim_funds_with_known_custom_tlvs(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds_with_known_custom_tlvs(::lightning::ln::PaymentPreimage(payment_preimage.data)) } -/// If a peer is disconnected we mark any channels with that peer as 'disabled'. -/// After some time, if channels are still disabled we need to broadcast a ChannelUpdate -/// to inform the network about the uselessness of these channels. -/// -/// This method handles all the details, and must be called roughly once per minute. -/// -/// Note that in some rare cases this may generate a `chain::Watch::update_channel` call. +/// Gets the node_id held by this ChannelManager +#[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.timer_tick_occurred() +pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::PublicKey { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_our_node_id(); + crate::c_types::PublicKey::from_rust(&ret) } -/// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect -/// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources -/// along the path (including in our own channel on which we received it). -/// Returns false if no payment was found to fail backwards, true if the process of failing the -/// HTLC backwards has been started. +/// Accepts a request to open a channel after a [`Event::OpenChannelRequest`]. +/// +/// The `temporary_channel_id` parameter indicates which inbound channel should be accepted, +/// and the `counterparty_node_id` parameter is the id of the peer which has requested to open +/// the channel. +/// +/// The `user_channel_id` parameter will be provided back in +/// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond +/// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call. +/// +/// Note that this method will return an error and reject the channel, if it requires support +/// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be +/// used to accept such channels. +/// +/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest +/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, payment_hash: *const [u8; 32]) -> bool { - let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash })); - ret +pub extern "C" fn ChannelManager_accept_inbound_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey, mut user_channel_id: crate::c_types::U128) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.accept_inbound_channel(&::lightning::ln::ChannelId(unsafe { *temporary_channel_id }), &counterparty_node_id.into_rust(), user_channel_id.into()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret } -/// Provides a payment preimage in response to a PaymentReceived event, returning true and -/// generating message events for the net layer to claim the payment, if possible. Thus, you -/// should probably kick the net layer to go send messages if this returns true! +/// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating +/// it as confirmed immediately. /// -/// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or -/// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentReceived` -/// event matches your expectation. If you fail to do so and call this method, you may provide -/// the sender \"proof-of-payment\" when they did not fulfill the full expected payment. +/// The `user_channel_id` parameter will be provided back in +/// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond +/// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call. /// -/// May panic if called except in response to a PaymentReceived event. +/// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel +/// and (if the counterparty agrees), enables forwarding of payments immediately. /// -/// [`create_inbound_payment`]: Self::create_inbound_payment -/// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash +/// This fully trusts that the counterparty has honestly and correctly constructed the funding +/// transaction and blindly assumes that it will eventually confirm. +/// +/// If it does not confirm before we decide to close the channel, or if the funding transaction +/// does not pay to the correct script the correct amount, *you will lose funds*. +/// +/// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest +/// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) -> bool { - let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data)); - ret +pub extern "C" fn ChannelManager_accept_inbound_channel_from_trusted_peer_0conf(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: *const [u8; 32], mut counterparty_node_id: crate::c_types::PublicKey, mut user_channel_id: crate::c_types::U128) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.accept_inbound_channel_from_trusted_peer_0conf(&::lightning::ln::ChannelId(unsafe { *temporary_channel_id }), &counterparty_node_id.into_rust(), user_channel_id.into()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; + local_ret } -/// Gets the node_id held by this ChannelManager +/// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and +/// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual +/// [`Bolt12Invoice`] once it is received. +/// +/// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by +/// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request. +/// The optional parameters are used in the builder, if `Some`: +/// - `quantity` for [`InvoiceRequest::quantity`] which must be set if +/// [`Offer::expects_quantity`] is `true`. +/// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and +/// - `payer_note` for [`InvoiceRequest::payer_note`]. +/// +/// If `max_total_routing_fee_msat` is not specified, The default from +/// [`RouteParameters::from_payment_params_and_value`] is applied. +/// +/// # Payment +/// +/// The provided `payment_id` is used to ensure that only one invoice is paid for the request +/// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has +/// been sent. +/// +/// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the +/// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the +/// payment will fail with an [`Event::InvoiceRequestFailed`]. +/// +/// # Privacy +/// +/// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`] +/// as the introduction node and a derived payer id for payer privacy. As such, currently, the +/// node must be announced. Otherwise, there is no way to find a path to the introduction node +/// in order to send the [`Bolt12Invoice`]. +/// +/// # Limitations +/// +/// Requires a direct connection to an introduction node in [`Offer::paths`] or to +/// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding +/// [`Bolt12Invoice::payment_paths`]. +/// +/// # Errors +/// +/// Errors if: +/// - a duplicate `payment_id` is provided given the caveats in the aforementioned link, +/// - the provided parameters are invalid for the offer, +/// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice +/// request. +/// +/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest +/// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity +/// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note +/// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder +/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice +/// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths +/// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.get_our_node_id(); - crate::c_types::PublicKey::from_rust(&ret) +pub extern "C" fn ChannelManager_pay_for_offer(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, offer: &crate::lightning::offers::offer::Offer, mut quantity: crate::c_types::derived::COption_u64Z, mut amount_msats: crate::c_types::derived::COption_u64Z, mut payer_note: crate::c_types::derived::COption_StrZ, mut payment_id: crate::c_types::ThirtyTwoBytes, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, mut max_total_routing_fee_msat: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_NoneBolt12SemanticErrorZ { + let mut local_quantity = if quantity.is_some() { Some( { quantity.take() }) } else { None }; + let mut local_amount_msats = if amount_msats.is_some() { Some( { amount_msats.take() }) } else { None }; + let mut local_payer_note = { /*payer_note*/ let payer_note_opt = payer_note; if payer_note_opt.is_none() { None } else { Some({ { { payer_note_opt.take() }.into_string() }})} }; + let mut local_max_total_routing_fee_msat = if max_total_routing_fee_msat.is_some() { Some( { max_total_routing_fee_msat.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_for_offer(offer.get_native_ref(), local_quantity, local_amount_msats, local_payer_note, ::lightning::ln::channelmanager::PaymentId(payment_id.data), retry_strategy.into_native(), local_max_total_routing_fee_msat); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() }; + local_ret } -/// Restores a single, given channel to normal operation after a -/// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update -/// operation. +/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion +/// message. +/// +/// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a +/// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding +/// [`PaymentPreimage`]. /// -/// All ChannelMonitor updates up to and including highest_applied_update_id must have been -/// fully committed in every copy of the given channels' ChannelMonitors. +/// # Limitations /// -/// Note that there is no effect to calling with a highest_applied_update_id other than the -/// current latest ChannelMonitorUpdate and one call to this function after multiple -/// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field -/// exists largely only to prevent races between this and concurrent update_monitor calls. +/// Requires a direct connection to an introduction node in [`Refund::paths`] or to +/// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each +/// node meeting the aforementioned criteria, but there's no guarantee that they will be +/// received and no retries will be made. /// -/// Thus, the anticipated use is, at a high level: -/// 1) You register a chain::Watch with this ChannelManager, -/// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of -/// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures -/// any time it cannot do so instantly, -/// 3) update(s) are applied to each remote copy of a ChannelMonitor, -/// 4) once all remote copies are updated, you call this function with the update_id that -/// completed, and once it is the latest the Channel will be re-enabled. +/// # Errors +/// +/// Errors if the parameterized [`Router`] is unable to create a blinded payment path or reply +/// path for the invoice. +/// +/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice +#[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManager, funding_txo: &crate::lightning::chain::transaction::OutPoint, mut highest_applied_update_id: u64) { - unsafe { &*this_arg.inner }.channel_monitor_updated(unsafe { &*funding_txo.inner }, highest_applied_update_id) +pub extern "C" fn ChannelManager_request_refund_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, refund: &crate::lightning::offers::refund::Refund) -> crate::c_types::derived::CResult_NoneBolt12SemanticErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_refund_payment(refund.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() }; + local_ret } /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing /// to pay us. /// /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the -/// [`PaymentHash`] and [`PaymentPreimage`] for you, returning the first and storing the second. +/// [`PaymentHash`] and [`PaymentPreimage`] for you. /// -/// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentReceived`], which -/// will have the [`PaymentReceived::payment_preimage`] field filled in. That should then be +/// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which +/// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with +/// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be /// passed directly to [`claim_funds`]. /// /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements. /// +/// Note that a malicious eavesdropper can intuit whether an inbound payment was created by +/// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime. +/// +/// # Note +/// +/// If you register an inbound payment with this method, then serialize the `ChannelManager`, then +/// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received. +/// +/// Errors if `min_value_msat` is greater than total bitcoin supply. +/// +/// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. +/// /// [`claim_funds`]: Self::claim_funds -/// [`PaymentReceived`]: events::Event::PaymentReceived -/// [`PaymentReceived::payment_preimage`]: events::Event::PaymentReceived::payment_preimage +/// [`PaymentClaimable`]: events::Event::PaymentClaimable +/// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose +/// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment +/// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut user_payment_id: u64) -> crate::c_types::derived::C2Tuple_PaymentHashPaymentSecretZ { +pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, user_payment_id); - let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1.0 }).into(); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is /// stored external to LDK. /// -/// A [`PaymentReceived`] event will only be generated if the [`PaymentSecret`] matches a +/// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least /// the `min_value_msat` provided here, if one is provided. /// -/// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) must be globally unique. This -/// method may return an Err if another payment with the same payment_hash is still pending. -/// -/// `user_payment_id` will be provided back in [`PaymentPurpose::InvoicePayment::user_payment_id`] events to -/// allow tracking of which events correspond with which calls to this and -/// [`create_inbound_payment`]. `user_payment_id` has no meaning inside of LDK, it is simply -/// copied to events and otherwise ignored. It may be used to correlate PaymentReceived events -/// with invoice metadata stored elsewhere. +/// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though +/// note that LDK will not stop you from registering duplicate payment hashes for inbound +/// payments. /// /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat` -/// before a [`PaymentReceived`] event will be generated, ensuring that we do not provide the +/// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the /// sender \"proof-of-payment\" unless they have paid the required amount. /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for @@ -1285,37 +3575,99 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage /// /// Note that we use block header time to time-out pending inbound payments (with some margin /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will -/// accept a payment and generate a [`PaymentReceived`] event for some time after the expiry. +/// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry. /// If you need exact expiry semantics, you should enforce them upon receipt of -/// [`PaymentReceived`]. +/// [`PaymentClaimable`]. +/// +/// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta` +/// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. +/// +/// Note that a malicious eavesdropper can intuit whether an inbound payment was created by +/// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime. /// -/// Pending inbound payments are stored in memory and in serialized versions of this -/// [`ChannelManager`]. If potentially unbounded numbers of inbound payments may exist and -/// space is limited, you may wish to rate-limit inbound payment creation. +/// # Note /// -/// May panic if `invoice_expiry_delta_secs` is greater than one year. +/// If you register an inbound payment with this method, then serialize the `ChannelManager`, then +/// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received. /// -/// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry` -/// set to at least [`MIN_FINAL_CLTV_EXPIRY`]. +/// Errors if `min_value_msat` is greater than total bitcoin supply. +/// +/// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. /// /// [`create_inbound_payment`]: Self::create_inbound_payment -/// [`PaymentReceived`]: events::Event::PaymentReceived -/// [`PaymentPurpose::InvoicePayment::user_payment_id`]: events::PaymentPurpose::InvoicePayment::user_payment_id +/// [`PaymentClaimable`]: events::Event::PaymentClaimable #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut user_payment_id: u64) -> crate::c_types::derived::CResult_PaymentSecretAPIErrorZ { +pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_ThirtyTwoBytesNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = unsafe { &*this_arg.inner }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, user_payment_id); + let mut local_min_final_cltv_expiry = if min_final_cltv_expiry.is_some() { Some( { min_final_cltv_expiry.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry); + 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( { () /*e*/ }).into() }; + local_ret +} + +/// Gets an LDK-generated payment preimage from a payment hash and payment secret that were +/// previously returned from [`create_inbound_payment`]. +/// +/// [`create_inbound_payment`]: Self::create_inbound_payment +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_get_payment_preimage(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_ThirtyTwoBytesAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_payment_preimage(::lightning::ln::PaymentHash(payment_hash.data), ::lightning::ln::PaymentSecret(payment_secret.data)); 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::util::errors::APIError::native_into(e) }).into() }; local_ret } -impl From for crate::lightning::util::events::MessageSendEventsProvider { +/// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids +/// are used when constructing the phantom invoice's route hints. +/// +/// [phantom node payments]: crate::sign::PhantomKeysManager +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_get_phantom_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> u64 { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_phantom_scid(); + ret +} + +/// Gets route hints for use in receiving [phantom node payments]. +/// +/// [phantom node payments]: crate::sign::PhantomKeysManager +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_get_phantom_route_hints(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::channelmanager::PhantomRouteHints { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_phantom_route_hints(); + crate::lightning::ln::channelmanager::PhantomRouteHints { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are +/// used when constructing the route hints for HTLCs intended to be intercepted. See +/// [`ChannelManager::forward_intercepted_htlc`]. +/// +/// Note that this method is not guaranteed to return unique values, you may need to call it a few +/// times to get a unique scid. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_get_intercept_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> u64 { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_intercept_scid(); + ret +} + +/// Gets inflight HTLC information by processing pending outbound payments that are in +/// our channels. May be used during pathfinding to account for in-use channel liquidity. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_compute_inflight_htlcs(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::routing::router::InFlightHtlcs { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.compute_inflight_htlcs(); + crate::lightning::routing::router::InFlightHtlcs { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +impl From for crate::lightning::events::MessageSendEventsProvider { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChannelManager_as_MessageSendEventsProvider(&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(); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); ret.free = Some(ChannelManager_free_void); ret } @@ -1323,9 +3675,9 @@ impl From for crate::lightning::util::events::MessageSendE /// Constructs a new MessageSendEventsProvider which calls the relevant methods on this_arg. /// This copies the `inner` pointer in this_arg and thus the returned MessageSendEventsProvider must be freed before this_arg is #[no_mangle] -pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::lightning::util::events::MessageSendEventsProvider { - crate::lightning::util::events::MessageSendEventsProvider { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, +pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::lightning::events::MessageSendEventsProvider { + crate::lightning::events::MessageSendEventsProvider { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events, } @@ -1333,17 +3685,17 @@ pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &Channel #[must_use] extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ { - let mut ret = >::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::MessageSendEvent::native_into(item) }); }; + let mut ret = >::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::events::MessageSendEvent::native_into(item) }); }; local_ret.into() } -impl From for crate::lightning::util::events::EventsProvider { +impl From for crate::lightning::events::EventsProvider { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChannelManager_as_EventsProvider(&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(); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); ret.free = Some(ChannelManager_free_void); ret } @@ -1351,24 +3703,24 @@ impl From for crate::lightning::util::events::EventsProvid /// Constructs a new EventsProvider which calls the relevant methods on this_arg. /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is #[no_mangle] -pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::lightning::util::events::EventsProvider { - crate::lightning::util::events::EventsProvider { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, +pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::lightning::events::EventsProvider { + crate::lightning::events::EventsProvider { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, process_pending_events: ChannelManager_EventsProvider_process_pending_events, } } -extern "C" fn ChannelManager_EventsProvider_process_pending_events(this_arg: *const c_void, mut handler: crate::lightning::util::events::EventHandler) { - >::process_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, handler) +extern "C" fn ChannelManager_EventsProvider_process_pending_events(this_arg: *const c_void, mut handler: crate::lightning::events::EventHandler) { + >::process_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, handler) } impl From for crate::lightning::chain::Listen { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChannelManager_as_Listen(&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(); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); ret.free = Some(ChannelManager_free_void); ret } @@ -1378,13 +3730,18 @@ impl From for crate::lightning::chain::Listen { #[no_mangle] pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::lightning::chain::Listen { crate::lightning::chain::Listen { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, + filtered_block_connected: ChannelManager_Listen_filtered_block_connected, block_connected: ChannelManager_Listen_block_connected, block_disconnected: ChannelManager_Listen_block_disconnected, } } +extern "C" fn ChannelManager_Listen_filtered_block_connected(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) { + let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); }; + >::filtered_block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height) +} extern "C" fn ChannelManager_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) { >::block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height) } @@ -1394,10 +3751,10 @@ extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void, impl From for crate::lightning::chain::Confirm { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChannelManager_as_Confirm(&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(); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); ret.free = Some(ChannelManager_free_void); ret } @@ -1407,7 +3764,7 @@ impl From for crate::lightning::chain::Confirm { #[no_mangle] pub extern "C" fn ChannelManager_as_Confirm(this_arg: &ChannelManager) -> crate::lightning::chain::Confirm { crate::lightning::chain::Confirm { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, transactions_confirmed: ChannelManager_Confirm_transactions_confirmed, transaction_unconfirmed: ChannelManager_Confirm_transaction_unconfirmed, @@ -1420,54 +3777,93 @@ extern "C" fn ChannelManager_Confirm_transactions_confirmed(this_arg: *const c_v let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); }; >::transactions_confirmed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height) } +extern "C" fn ChannelManager_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) { + >::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap()) +} extern "C" fn ChannelManager_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) { >::best_block_updated(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height) } #[must_use] -extern "C" fn ChannelManager_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ { +extern "C" fn ChannelManager_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_ThirtyTwoBytesu32COption_ThirtyTwoBytesZZZ { let mut ret = >::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); }; + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_2.unwrap().as_ref() } }) }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0.as_ref() }, orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); }; local_ret.into() } -extern "C" fn ChannelManager_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) { - >::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap()) -} -/// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool -/// indicating whether persistence is necessary. Only one listener on -/// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken -/// up. -/// Note that the feature `allow_wallclock_use` must be enabled to use this function. +/// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or +/// may have events that need processing. +/// +/// In order to check if this [`ChannelManager`] needs persisting, call +/// [`Self::get_and_clear_needs_persistence`]. +/// +/// Note that callbacks registered on the [`Future`] MUST NOT call back into this +/// [`ChannelManager`] and should instead register actions to be taken later. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_await_persistable_update_timeout(this_arg: &ChannelManager, mut max_wait: u64) -> bool { - let mut ret = unsafe { &*this_arg.inner }.await_persistable_update_timeout(std::time::Duration::from_secs(max_wait)); - ret +pub extern "C" fn ChannelManager_get_event_or_persistence_needed_future(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::util::wakers::Future { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_event_or_persistence_needed_future(); + crate::lightning::util::wakers::Future { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Blocks until ChannelManager needs to be persisted. Only one listener on -/// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken -/// up. +/// Returns true if this [`ChannelManager`] needs to be persisted. +#[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.await_persistable_update() +pub extern "C" fn ChannelManager_get_and_clear_needs_persistence(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_needs_persistence(); + ret } /// Gets the latest best block which was connected either via the [`chain::Listen`] or /// [`chain::Confirm`] interfaces. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_current_best_block(this_arg: &ChannelManager) -> crate::lightning::chain::BestBlock { - let mut ret = unsafe { &*this_arg.inner }.current_best_block(); - crate::lightning::chain::BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true } +pub extern "C" fn ChannelManager_current_best_block(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::chain::BestBlock { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block(); + crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`NodeFeatures`] flags that are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_node_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::NodeFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.node_features(); + crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_channel_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_features(); + crate::lightning::ln::features::ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_channel_type_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelTypeFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_type_features(); + crate::lightning::ln::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`InitFeatures`] flags that are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_init_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::InitFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.init_features(); + crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } impl From for crate::lightning::ln::msgs::ChannelMessageHandler { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChannelManager_as_ChannelMessageHandler(&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(); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); ret.free = Some(ChannelManager_free_void); ret } @@ -1477,15 +3873,30 @@ impl From for crate::lightning::ln::msgs::ChannelMessageHa #[no_mangle] pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::lightning::ln::msgs::ChannelMessageHandler { crate::lightning::ln::msgs::ChannelMessageHandler { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, handle_open_channel: ChannelManager_ChannelMessageHandler_handle_open_channel, + handle_open_channel_v2: ChannelManager_ChannelMessageHandler_handle_open_channel_v2, handle_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel, + handle_accept_channel_v2: ChannelManager_ChannelMessageHandler_handle_accept_channel_v2, handle_funding_created: ChannelManager_ChannelMessageHandler_handle_funding_created, handle_funding_signed: ChannelManager_ChannelMessageHandler_handle_funding_signed, - handle_funding_locked: ChannelManager_ChannelMessageHandler_handle_funding_locked, + handle_channel_ready: ChannelManager_ChannelMessageHandler_handle_channel_ready, handle_shutdown: ChannelManager_ChannelMessageHandler_handle_shutdown, handle_closing_signed: ChannelManager_ChannelMessageHandler_handle_closing_signed, + handle_stfu: ChannelManager_ChannelMessageHandler_handle_stfu, + handle_splice: ChannelManager_ChannelMessageHandler_handle_splice, + handle_splice_ack: ChannelManager_ChannelMessageHandler_handle_splice_ack, + handle_splice_locked: ChannelManager_ChannelMessageHandler_handle_splice_locked, + handle_tx_add_input: ChannelManager_ChannelMessageHandler_handle_tx_add_input, + handle_tx_add_output: ChannelManager_ChannelMessageHandler_handle_tx_add_output, + handle_tx_remove_input: ChannelManager_ChannelMessageHandler_handle_tx_remove_input, + handle_tx_remove_output: ChannelManager_ChannelMessageHandler_handle_tx_remove_output, + handle_tx_complete: ChannelManager_ChannelMessageHandler_handle_tx_complete, + handle_tx_signatures: ChannelManager_ChannelMessageHandler_handle_tx_signatures, + handle_tx_init_rbf: ChannelManager_ChannelMessageHandler_handle_tx_init_rbf, + handle_tx_ack_rbf: ChannelManager_ChannelMessageHandler_handle_tx_ack_rbf, + handle_tx_abort: ChannelManager_ChannelMessageHandler_handle_tx_abort, handle_update_add_htlc: ChannelManager_ChannelMessageHandler_handle_update_add_htlc, handle_update_fulfill_htlc: ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc, handle_update_fail_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_htlc, @@ -1499,106 +3910,365 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana handle_channel_reestablish: ChannelManager_ChannelMessageHandler_handle_channel_reestablish, handle_channel_update: ChannelManager_ChannelMessageHandler_handle_channel_update, handle_error: ChannelManager_ChannelMessageHandler_handle_error, - MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider { - this_arg: unsafe { (*this_arg).inner as *mut c_void }, + provided_node_features: ChannelManager_ChannelMessageHandler_provided_node_features, + provided_init_features: ChannelManager_ChannelMessageHandler_provided_init_features, + get_chain_hashes: ChannelManager_ChannelMessageHandler_get_chain_hashes, + MessageSendEventsProvider: crate::lightning::events::MessageSendEventsProvider { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events, }, } } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::OpenChannel) { - >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannel) { + >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel_v2(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannelV2) { + >::handle_open_channel_v2(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannel) { + >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::AcceptChannel) { - >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel_v2(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannelV2) { + >::handle_accept_channel_v2(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) { - >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) { + >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingSigned) { - >::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingSigned) { + >::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_locked(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingLocked) { - >::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_ready(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReady) { + >::handle_channel_ready(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, their_features: &crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::Shutdown) { - >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*their_features.inner }, unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Shutdown) { + >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) { - >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) { + >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateAddHTLC) { - >::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_stfu(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Stfu) { + >::handle_stfu(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFulfillHTLC) { - >::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_splice(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Splice) { + >::handle_splice(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailHTLC) { - >::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_splice_ack(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::SpliceAck) { + >::handle_splice_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailMalformedHTLC) { - >::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_splice_locked(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::SpliceLocked) { + >::handle_splice_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::CommitmentSigned) { - >::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_add_input(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAddInput) { + >::handle_tx_add_input(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::RevokeAndACK) { - >::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_add_output(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAddOutput) { + >::handle_tx_add_output(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFee) { - >::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_remove_input(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxRemoveInput) { + >::handle_tx_remove_input(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) { - >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_remove_output(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxRemoveOutput) { + >::handle_tx_remove_output(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_update(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelUpdate) { - >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_complete(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxComplete) { + >::handle_tx_complete(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReestablish) { - >::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxSignatures) { + >::handle_tx_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), no_connection_possible) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_init_rbf(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxInitRbf) { + >::handle_tx_init_rbf(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, init_msg: &crate::lightning::ln::msgs::Init) { - >::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*init_msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_ack_rbf(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAckRbf) { + >::handle_tx_ack_rbf(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ErrorMessage) { - >::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner }) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_abort(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAbort) { + >::handle_tx_abort(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateAddHTLC) { + >::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFulfillHTLC) { + >::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailHTLC) { + >::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailMalformedHTLC) { + >::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::CommitmentSigned) { + >::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::RevokeAndACK) { + >::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFee) { + >::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) { + >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) { + >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust()) +} +#[must_use] +extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref(), inbound); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReestablish) { + >::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_update(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelUpdate) { + >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ErrorMessage) { + >::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) +} +#[must_use] +extern "C" fn ChannelManager_ChannelMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures { + let mut ret = >::provided_node_features(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); + crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} +#[must_use] +extern "C" fn ChannelManager_ChannelMessageHandler_provided_init_features(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) -> crate::lightning::ln::features::InitFeatures { + let mut ret = >::provided_init_features(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust()); + crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} +#[must_use] +extern "C" fn ChannelManager_ChannelMessageHandler_get_chain_hashes(this_arg: *const c_void) -> crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ { + let mut ret = >::get_chain_hashes(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ::None } else { crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ::Some( { let mut local_ret_0 = Vec::new(); for mut item in ret.unwrap().drain(..) { local_ret_0.push( { crate::c_types::ThirtyTwoBytes { data: *item.as_ref() } }); }; local_ret_0.into() }) }; + local_ret } +impl From for crate::lightning::onion_message::offers::OffersMessageHandler { + fn from(obj: nativeChannelManager) -> Self { + let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = ChannelManager_as_OffersMessageHandler(&rust_obj); + // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn + core::mem::forget(rust_obj); + ret.free = Some(ChannelManager_free_void); + ret + } +} +/// Constructs a new OffersMessageHandler which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned OffersMessageHandler must be freed before this_arg is #[no_mangle] -/// Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read -pub extern "C" fn ChannelManager_write(obj: &ChannelManager) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) +pub extern "C" fn ChannelManager_as_OffersMessageHandler(this_arg: &ChannelManager) -> crate::lightning::onion_message::offers::OffersMessageHandler { + crate::lightning::onion_message::offers::OffersMessageHandler { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + handle_message: ChannelManager_OffersMessageHandler_handle_message, + release_pending_messages: ChannelManager_OffersMessageHandler_release_pending_messages, + } +} + +#[must_use] +extern "C" fn ChannelManager_OffersMessageHandler_handle_message(this_arg: *const c_void, mut message: crate::lightning::onion_message::offers::OffersMessage) -> crate::c_types::derived::COption_OffersMessageZ { + let mut ret = >::handle_message(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, message.into_native()); + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_OffersMessageZ::None } else { crate::c_types::derived::COption_OffersMessageZ::Some( { crate::lightning::onion_message::offers::OffersMessage::native_into(ret.unwrap()) }) }; + local_ret +} +#[must_use] +extern "C" fn ChannelManager_OffersMessageHandler_release_pending_messages(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OffersMessageDestinationBlindedPathZZ { + let mut ret = >::release_pending_messages(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_2 = crate::lightning::blinded_path::BlindedPath { inner: if orig_ret_0_2.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((orig_ret_0_2.unwrap())) } }, is_owned: true }; let mut local_ret_0 = (crate::lightning::onion_message::offers::OffersMessage::native_into(orig_ret_0_0), crate::lightning::onion_message::messenger::Destination::native_into(orig_ret_0_1), local_orig_ret_0_2).into(); local_ret_0 }); }; + local_ret.into() +} + +/// Fetches the set of [`InitFeatures`] flags that are provided by or required by +/// [`ChannelManager`]. +#[no_mangle] +pub extern "C" fn provided_init_features(config: &crate::lightning::util::config::UserConfig) -> crate::lightning::ln::features::InitFeatures { + let mut ret = lightning::ln::channelmanager::provided_init_features(config.get_native_ref()); + crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +#[no_mangle] +/// Serialize the CounterpartyForwardingInfo object into a byte array which can be read by CounterpartyForwardingInfo_read +pub extern "C" fn CounterpartyForwardingInfo_write(obj: &crate::lightning::ln::channelmanager::CounterpartyForwardingInfo) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn CounterpartyForwardingInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCounterpartyForwardingInfo) }) +} +#[no_mangle] +/// Read a CounterpartyForwardingInfo from a byte array, created by CounterpartyForwardingInfo_write +pub extern "C" fn CounterpartyForwardingInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyForwardingInfoDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::CounterpartyForwardingInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the ChannelCounterparty object into a byte array which can be read by ChannelCounterparty_read +pub extern "C" fn ChannelCounterparty_write(obj: &crate::lightning::ln::channelmanager::ChannelCounterparty) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn ChannelCounterparty_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelCounterparty) }) +} +#[no_mangle] +/// Read a ChannelCounterparty from a byte array, created by ChannelCounterparty_write +pub extern "C" fn ChannelCounterparty_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelCounterpartyDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::ChannelCounterparty { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the ChannelDetails object into a byte array which can be read by ChannelDetails_read +pub extern "C" fn ChannelDetails_write(obj: &crate::lightning::ln::channelmanager::ChannelDetails) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn ChannelDetails_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelDetails) }) +} +#[no_mangle] +/// Read a ChannelDetails from a byte array, created by ChannelDetails_write +pub extern "C" fn ChannelDetails_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelDetailsDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the PhantomRouteHints object into a byte array which can be read by PhantomRouteHints_read +pub extern "C" fn PhantomRouteHints_write(obj: &crate::lightning::ln::channelmanager::PhantomRouteHints) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn PhantomRouteHints_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePhantomRouteHints) }) +} +#[no_mangle] +/// Read a PhantomRouteHints from a byte array, created by PhantomRouteHints_write +pub extern "C" fn PhantomRouteHints_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PhantomRouteHintsDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PhantomRouteHints { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the BlindedForward object into a byte array which can be read by BlindedForward_read +pub extern "C" fn BlindedForward_write(obj: &crate::lightning::ln::channelmanager::BlindedForward) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn BlindedForward_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeBlindedForward) }) +} +#[no_mangle] +/// Read a BlindedForward from a byte array, created by BlindedForward_write +pub extern "C" fn BlindedForward_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedForwardDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::BlindedForward { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the PendingHTLCRouting object into a byte array which can be read by PendingHTLCRouting_read +pub extern "C" fn PendingHTLCRouting_write(obj: &crate::lightning::ln::channelmanager::PendingHTLCRouting) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[allow(unused)] +pub(crate) extern "C" fn PendingHTLCRouting_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + PendingHTLCRouting_write(unsafe { &*(obj as *const PendingHTLCRouting) }) +} +#[no_mangle] +/// Read a PendingHTLCRouting from a byte array, created by PendingHTLCRouting_write +pub extern "C" fn PendingHTLCRouting_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PendingHTLCRoutingDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PendingHTLCRouting::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the PendingHTLCInfo object into a byte array which can be read by PendingHTLCInfo_read +pub extern "C" fn PendingHTLCInfo_write(obj: &crate::lightning::ln::channelmanager::PendingHTLCInfo) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] +pub(crate) extern "C" fn PendingHTLCInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePendingHTLCInfo) }) +} +#[no_mangle] +/// Read a PendingHTLCInfo from a byte array, created by PendingHTLCInfo_write +pub extern "C" fn PendingHTLCInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PendingHTLCInfoDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PendingHTLCInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} +#[no_mangle] +/// Serialize the BlindedFailure object into a byte array which can be read by BlindedFailure_read +pub extern "C" fn BlindedFailure_write(obj: &crate::lightning::ln::channelmanager::BlindedFailure) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[allow(unused)] +pub(crate) extern "C" fn BlindedFailure_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + BlindedFailure_write(unsafe { &*(obj as *const BlindedFailure) }) +} +#[no_mangle] +/// Read a BlindedFailure from a byte array, created by BlindedFailure_write +pub extern "C" fn BlindedFailure_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedFailureDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::BlindedFailure::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res } #[no_mangle] +/// Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read +pub extern "C" fn ChannelManager_write(obj: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) +} +#[allow(unused)] pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelManager) }) } +#[no_mangle] +/// Serialize the ChannelShutdownState object into a byte array which can be read by ChannelShutdownState_read +pub extern "C" fn ChannelShutdownState_write(obj: &crate::lightning::ln::channelmanager::ChannelShutdownState) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[allow(unused)] +pub(crate) extern "C" fn ChannelShutdownState_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + ChannelShutdownState_write(unsafe { &*(obj as *const ChannelShutdownState) }) +} +#[no_mangle] +/// Read a ChannelShutdownState from a byte array, created by ChannelShutdownState_write +pub extern "C" fn ChannelShutdownState_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelShutdownStateDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::ChannelShutdownState::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport; -type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger>; +pub(crate) type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger>; /// Arguments for the creation of a ChannelManager that are not deserialized. /// /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation /// is: -/// 1) Deserialize all stored ChannelMonitors. -/// 2) Deserialize the ChannelManager by filling in this struct and calling: -/// <(BlockHash, ChannelManager)>::read(reader, args) -/// This may result in closing some Channels if the ChannelMonitor is newer than the stored -/// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted. -/// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same -/// way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and -/// ChannelMonitor::get_funding_txo(). -/// 4) Reconnect blocks on your ChannelMonitors. -/// 5) Disconnect/connect blocks on the ChannelManager. -/// 6) Move the ChannelMonitors into your local chain::Watch. -/// -/// Note that the ordering of #4-6 is not of importance, however all three must occur before you -/// call any other methods on the newly-deserialized ChannelManager. +/// 1) Deserialize all stored [`ChannelMonitor`]s. +/// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling: +/// `<(BlockHash, ChannelManager)>::read(reader, args)` +/// This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored +/// [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted. +/// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the +/// same way you would handle a [`chain::Filter`] call using +/// [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`]. +/// 4) Reconnect blocks on your [`ChannelMonitor`]s. +/// 5) Disconnect/connect blocks on the [`ChannelManager`]. +/// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk. +/// Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you +/// will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in +/// the next step. +/// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a +/// [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`]. +/// +/// Note that the ordering of #4-7 is not of importance, however all four must occur before you +/// call any other methods on the newly-deserialized [`ChannelManager`]. /// /// Note that because some channels may be closed during deserialization, it is critical that you /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to @@ -1606,6 +4276,8 @@ type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will /// not force-close the same channels but consider them live), you may end up revoking a state for /// which you've already broadcasted the transaction. +/// +/// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor #[must_use] #[repr(C)] pub struct ChannelManagerReadArgs { @@ -1624,7 +4296,7 @@ pub struct ChannelManagerReadArgs { impl Drop for ChannelManagerReadArgs { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelManagerReadArgs>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1633,40 +4305,68 @@ impl Drop for ChannelManagerReadArgs { pub extern "C" fn ChannelManagerReadArgs_free(this_obj: ChannelManagerReadArgs) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) { - unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs); } +pub(crate) extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs) }; } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelManagerReadArgs { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManagerReadArgs { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManagerReadArgs { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs { assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); ret } } +/// A cryptographically secure source of entropy. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_entropy_source(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::EntropySource { + let mut inner_val = &mut this_ptr.get_native_mut_ref().entropy_source; + inner_val +} +/// A cryptographically secure source of entropy. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_entropy_source(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::EntropySource) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.entropy_source = val; +} +/// A signer that is able to perform node-scoped cryptographic operations. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_node_signer(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::NodeSigner { + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signer; + inner_val +} +/// A signer that is able to perform node-scoped cryptographic operations. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_node_signer(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::NodeSigner) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signer = val; +} /// The keys provider which will give us relevant keys. Some keys will be loaded during /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel /// signing data. #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::KeysInterface { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.keys_manager; +pub extern "C" fn ChannelManagerReadArgs_get_signer_provider(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::SignerProvider { + let mut inner_val = &mut this_ptr.get_native_mut_ref().signer_provider; inner_val } /// The keys provider which will give us relevant keys. Some keys will be loaded during /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel /// signing data. #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::KeysInterface) { - unsafe { &mut *this_ptr.inner }.keys_manager = val; +pub extern "C" fn ChannelManagerReadArgs_set_signer_provider(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::SignerProvider) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signer_provider = val; } /// The fee_estimator for use in the ChannelManager in the future. /// /// No calls to the FeeEstimator will be made during deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::FeeEstimator { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_estimator; + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_estimator; inner_val } /// The fee_estimator for use in the ChannelManager in the future. @@ -1674,7 +4374,7 @@ pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelMan /// No calls to the FeeEstimator will be made during deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::FeeEstimator) { - unsafe { &mut *this_ptr.inner }.fee_estimator = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_estimator = val; } /// The chain::Watch for use in the ChannelManager in the future. /// @@ -1683,7 +4383,7 @@ pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut Channe /// chain::Watch after deserializing this ChannelManager. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::Watch { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_monitor; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_monitor; inner_val } /// The chain::Watch for use in the ChannelManager in the future. @@ -1693,14 +4393,14 @@ pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelMan /// chain::Watch after deserializing this ChannelManager. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_set_chain_monitor(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::Watch) { - unsafe { &mut *this_ptr.inner }.chain_monitor = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_monitor = val; } /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be /// used to broadcast the latest local commitment transactions of channels which must be /// force-closed during deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::BroadcasterInterface { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.tx_broadcaster; + let mut inner_val = &mut this_ptr.get_native_mut_ref().tx_broadcaster; inner_val } /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be @@ -1708,50 +4408,67 @@ pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelMa /// force-closed during deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::BroadcasterInterface) { - unsafe { &mut *this_ptr.inner }.tx_broadcaster = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.tx_broadcaster = val; +} +/// The router which will be used in the ChannelManager in the future for finding routes +/// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. +/// +/// No calls to the router will be made during deserialization. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_router(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::routing::router::Router { + let mut inner_val = &mut this_ptr.get_native_mut_ref().router; + inner_val +} +/// The router which will be used in the ChannelManager in the future for finding routes +/// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. +/// +/// No calls to the router will be made during deserialization. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_router(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::routing::router::Router) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.router = val; } /// The Logger for use in the ChannelManager and which may be used to log information during /// deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_get_logger(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::util::logger::Logger { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.logger; + let mut inner_val = &mut this_ptr.get_native_mut_ref().logger; inner_val } /// The Logger for use in the ChannelManager and which may be used to log information during /// deserialization. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_set_logger(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::logger::Logger) { - unsafe { &mut *this_ptr.inner }.logger = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.logger = val; } /// Default settings used for new channels. Any existing channels will continue to use the /// runtime settings which were stored when the ChannelManager was serialized. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelManagerReadArgs) -> crate::lightning::util::config::UserConfig { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.default_config; - crate::lightning::util::config::UserConfig { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().default_config; + crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::util::config::UserConfig<>) as *mut _) }, is_owned: false } } /// Default settings used for new channels. Any existing channels will continue to use the /// runtime settings which were stored when the ChannelManager was serialized. #[no_mangle] pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::config::UserConfig) { - unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.default_config = *unsafe { Box::from_raw(val.take_inner()) }; } /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor /// HashMap for you. This is primarily useful for C bindings where it is not practical to /// populate a HashMap directly from C. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> ChannelManagerReadArgs { - let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { unsafe { &mut *item.inner } }); }; - let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors); - ChannelManagerReadArgs { inner: Box::into_raw(Box::new(ret)), is_owned: true } +pub extern "C" fn ChannelManagerReadArgs_new(mut entropy_source: crate::lightning::sign::EntropySource, mut node_signer: crate::lightning::sign::NodeSigner, mut signer_provider: crate::lightning::sign::SignerProvider, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> crate::lightning::ln::channelmanager::ChannelManagerReadArgs { + let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { item.get_native_mut_ref() }); }; + let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors); + crate::lightning::ln::channelmanager::ChannelManagerReadArgs { inner: ObjOps::heap_alloc(ret), is_owned: true } } #[no_mangle] -/// Read a C2Tuple_BlockHashChannelManagerZ from a byte array, created by C2Tuple_BlockHashChannelManagerZ_write -pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::lightning::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ { +/// Read a C2Tuple_ThirtyTwoBytesChannelManagerZ from a byte array, created by C2Tuple_ThirtyTwoBytesChannelManagerZ_write +pub extern "C" fn C2Tuple_ThirtyTwoBytesChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::lightning::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ { let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) }; - let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::ln::channelmanager::ChannelManager { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_res_0_0.as_ref() }, crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res }