X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-c-bindings;a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning%2Fln%2Fpeer_handler.rs;h=9d712c84d6ffe8ca0b2b1f917e35da2153f2ee42;hp=6cc942df8ed52c92ae96b0f4318fbaff7514b691;hb=1eaf50a3d9f777b462ff1817678473567a00eb75;hpb=2d97d367136737b0a3bcda1312354aa37f9f215c diff --git a/lightning-c-bindings/src/lightning/ln/peer_handler.rs b/lightning-c-bindings/src/lightning/ln/peer_handler.rs index 6cc942d..9d712c8 100644 --- a/lightning-c-bindings/src/lightning/ln/peer_handler.rs +++ b/lightning-c-bindings/src/lightning/ln/peer_handler.rs @@ -14,13 +14,92 @@ //! call into the provided message handlers (probably a ChannelManager and NetGraphmsgHandler) with messages //! they should handle, and encoding/sending response messages. -use std::ffi::c_void; +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; +/// Handler for BOLT1-compliant messages. +#[repr(C)] +pub struct CustomMessageHandler { + /// An opaque pointer which is passed to your function implementations as an argument. + /// This has no meaning in the LDK, and can be NULL or any other value. + pub this_arg: *mut c_void, + /// Called with the message type that was received and the buffer to be read. + /// Can return a `MessageHandlingError` if the message could not be handled. + #[must_use] + pub handle_custom_message: extern "C" fn (this_arg: *const c_void, msg: crate::lightning::ln::wire::Type, sender_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneLightningErrorZ, + /// Gets the list of pending messages which were generated by the custom message + /// handler, clearing the list in the process. The first tuple element must + /// correspond to the intended recipients node ids. If no connection to one of the + /// specified node does not exist, the message is simply not sent to it. + #[must_use] + pub get_and_clear_pending_msg: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_PublicKeyTypeZZ, + /// Implementation of CustomMessageReader for this object. + pub CustomMessageReader: crate::lightning::ln::wire::CustomMessageReader, + /// Frees any resources associated with this object given its this_arg pointer. + /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + pub free: Option, +} +unsafe impl Send for CustomMessageHandler {} +unsafe impl Sync for CustomMessageHandler {} +#[no_mangle] +pub(crate) extern "C" fn CustomMessageHandler_clone_fields(orig: &CustomMessageHandler) -> CustomMessageHandler { + CustomMessageHandler { + this_arg: orig.this_arg, + handle_custom_message: Clone::clone(&orig.handle_custom_message), + get_and_clear_pending_msg: Clone::clone(&orig.get_and_clear_pending_msg), + CustomMessageReader: crate::lightning::ln::wire::CustomMessageReader_clone_fields(&orig.CustomMessageReader), + free: Clone::clone(&orig.free), + } +} +impl lightning::ln::wire::CustomMessageReader for CustomMessageHandler { + type CustomMessage = crate::lightning::ln::wire::Type; + fn read(&self, mut message_type: u16, mut buffer: &mut R) -> Result, lightning::ln::msgs::DecodeError> { + let mut ret = (self.CustomMessageReader.read)(self.CustomMessageReader.this_arg, message_type, crate::c_types::u8slice::from_vec(&crate::c_types::reader_to_vec(buffer))); + let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = { /* (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ let ret_0_opt = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }); { } if ret_0_opt.is_none() { None } else { Some({ ret_0_opt.take() }) } }; local_ret_0 }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; + local_ret + } +} + +use lightning::ln::peer_handler::CustomMessageHandler as rustCustomMessageHandler; +impl rustCustomMessageHandler for CustomMessageHandler { + fn handle_custom_message(&self, mut msg: crate::lightning::ln::wire::Type, mut sender_node_id: &bitcoin::secp256k1::key::PublicKey) -> Result<(), lightning::ln::msgs::LightningError> { + let mut ret = (self.handle_custom_message)(self.this_arg, Into::into(msg), crate::c_types::PublicKey::from_rust(&sender_node_id)); + let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; + local_ret + } + fn get_and_clear_pending_msg(&self) -> Vec<(bitcoin::secp256k1::key::PublicKey, crate::lightning::ln::wire::Type)> { + let mut ret = (self.get_and_clear_pending_msg)(self.this_arg); + let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item.to_rust(); let mut local_ret_0 = (orig_ret_0_0.into_rust(), orig_ret_0_1); local_ret_0 }); }; + local_ret + } +} + +// We're essentially a pointer already, or at least a set of pointers, so allow us to be used +// directly as a Deref trait in higher-level structs: +impl core::ops::Deref for CustomMessageHandler { + type Target = Self; + fn deref(&self) -> &Self { + self + } +} +/// Calls the free function if one is set +#[no_mangle] +pub extern "C" fn CustomMessageHandler_free(this_ptr: CustomMessageHandler) { } +impl Drop for CustomMessageHandler { + fn drop(&mut self) { + if let Some(f) = self.free { + f(self.this_arg); + } + } +} use lightning::ln::peer_handler::IgnoringMessageHandler as nativeIgnoringMessageHandlerImport; -type nativeIgnoringMessageHandler = nativeIgnoringMessageHandlerImport; +pub(crate) type nativeIgnoringMessageHandler = nativeIgnoringMessageHandlerImport; /// A dummy struct which implements `RoutingMessageHandler` without storing any routing information /// or doing any processing. You can provide one of these as the route_handler in a MessageHandler. @@ -42,7 +121,7 @@ pub struct IgnoringMessageHandler { impl Drop for IgnoringMessageHandler { fn drop(&mut self) { if self.is_owned && !<*mut nativeIgnoringMessageHandler>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -51,16 +130,22 @@ impl Drop for IgnoringMessageHandler { pub extern "C" fn IgnoringMessageHandler_free(this_obj: IgnoringMessageHandler) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn IgnoringMessageHandler_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn IgnoringMessageHandler_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeIgnoringMessageHandler); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl IgnoringMessageHandler { + pub(crate) fn get_native_ref(&self) -> &'static nativeIgnoringMessageHandler { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeIgnoringMessageHandler { + 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 nativeIgnoringMessageHandler { 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 } } @@ -68,15 +153,15 @@ impl IgnoringMessageHandler { #[must_use] #[no_mangle] pub extern "C" fn IgnoringMessageHandler_new() -> IgnoringMessageHandler { - IgnoringMessageHandler { inner: Box::into_raw(Box::new(nativeIgnoringMessageHandler { - })), is_owned: true } + IgnoringMessageHandler { inner: ObjOps::heap_alloc(nativeIgnoringMessageHandler { + }), is_owned: true } } impl From for crate::lightning::util::events::MessageSendEventsProvider { fn from(obj: nativeIgnoringMessageHandler) -> Self { - let mut rust_obj = IgnoringMessageHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = IgnoringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = IgnoringMessageHandler_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(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(IgnoringMessageHandler_free_void); ret } @@ -86,7 +171,7 @@ impl From for crate::lightning::util::events::Mess #[no_mangle] pub extern "C" fn IgnoringMessageHandler_as_MessageSendEventsProvider(this_arg: &IgnoringMessageHandler) -> crate::lightning::util::events::MessageSendEventsProvider { crate::lightning::util::events::MessageSendEventsProvider { - 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, get_and_clear_pending_msg_events: IgnoringMessageHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, } @@ -101,10 +186,10 @@ extern "C" fn IgnoringMessageHandler_MessageSendEventsProvider_get_and_clear_pen impl From for crate::lightning::ln::msgs::RoutingMessageHandler { fn from(obj: nativeIgnoringMessageHandler) -> Self { - let mut rust_obj = IgnoringMessageHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = IgnoringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = IgnoringMessageHandler_as_RoutingMessageHandler(&rust_obj); // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn - rust_obj.inner = std::ptr::null_mut(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(IgnoringMessageHandler_free_void); ret } @@ -114,12 +199,11 @@ impl From for crate::lightning::ln::msgs::RoutingM #[no_mangle] pub extern "C" fn IgnoringMessageHandler_as_RoutingMessageHandler(this_arg: &IgnoringMessageHandler) -> crate::lightning::ln::msgs::RoutingMessageHandler { crate::lightning::ln::msgs::RoutingMessageHandler { - 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_node_announcement: IgnoringMessageHandler_RoutingMessageHandler_handle_node_announcement, handle_channel_announcement: IgnoringMessageHandler_RoutingMessageHandler_handle_channel_announcement, handle_channel_update: IgnoringMessageHandler_RoutingMessageHandler_handle_channel_update, - handle_htlc_fail_channel_update: IgnoringMessageHandler_RoutingMessageHandler_handle_htlc_fail_channel_update, get_next_channel_announcements: IgnoringMessageHandler_RoutingMessageHandler_get_next_channel_announcements, get_next_node_announcements: IgnoringMessageHandler_RoutingMessageHandler_get_next_node_announcements, sync_routing_table: IgnoringMessageHandler_RoutingMessageHandler_sync_routing_table, @@ -128,7 +212,7 @@ pub extern "C" fn IgnoringMessageHandler_as_RoutingMessageHandler(this_arg: &Ign handle_query_channel_range: IgnoringMessageHandler_RoutingMessageHandler_handle_query_channel_range, handle_query_short_channel_ids: IgnoringMessageHandler_RoutingMessageHandler_handle_query_short_channel_ids, MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider { - 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, get_and_clear_pending_msg_events: IgnoringMessageHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, }, @@ -137,69 +221,138 @@ pub extern "C" fn IgnoringMessageHandler_as_RoutingMessageHandler(this_arg: &Ign #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_node_announcement(this_arg: *const c_void, _msg: &crate::lightning::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ { - let mut ret = >::handle_node_announcement(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, unsafe { &*_msg.inner }); - 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::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = >::handle_node_announcement(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, _msg.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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_channel_announcement(this_arg: *const c_void, _msg: &crate::lightning::ln::msgs::ChannelAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ { - let mut ret = >::handle_channel_announcement(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, unsafe { &*_msg.inner }); - 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::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = >::handle_channel_announcement(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, _msg.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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_channel_update(this_arg: *const c_void, _msg: &crate::lightning::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_boolLightningErrorZ { - let mut ret = >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, unsafe { &*_msg.inner }); - 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::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, _msg.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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } -extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_htlc_fail_channel_update(this_arg: *const c_void, _update: &crate::lightning::ln::msgs::HTLCFailChannelUpdate) { - >::handle_htlc_fail_channel_update(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_update.to_native()) -} #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_get_next_channel_announcements(this_arg: *const c_void, mut _starting_point: u64, mut _batch_amount: u8) -> crate::c_types::derived::CVec_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ { let mut ret = >::get_next_channel_announcements(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, _starting_point, _batch_amount); - 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_1 = crate::lightning::ln::msgs::ChannelUpdate { inner: if orig_ret_0_1.is_none() { std::ptr::null_mut() } else { { Box::into_raw(Box::new((orig_ret_0_1.unwrap()))) } }, is_owned: true }; let mut local_orig_ret_0_2 = crate::lightning::ln::msgs::ChannelUpdate { inner: if orig_ret_0_2.is_none() { std::ptr::null_mut() } else { { Box::into_raw(Box::new((orig_ret_0_2.unwrap()))) } }, is_owned: true }; let mut local_ret_0 = (crate::lightning::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(orig_ret_0_0)), is_owned: true }, local_orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); }; + 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_1 = crate::lightning::ln::msgs::ChannelUpdate { inner: if orig_ret_0_1.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((orig_ret_0_1.unwrap())) } }, is_owned: true }; let mut local_orig_ret_0_2 = crate::lightning::ln::msgs::ChannelUpdate { 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::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(orig_ret_0_0), is_owned: true }, local_orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); }; local_ret.into() } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_get_next_node_announcements(this_arg: *const c_void, mut _starting_point: crate::c_types::PublicKey, mut _batch_amount: u8) -> crate::c_types::derived::CVec_NodeAnnouncementZ { let mut local__starting_point_base = if _starting_point.is_null() { None } else { Some( { _starting_point.into_rust() }) }; let mut local__starting_point = local__starting_point_base.as_ref(); let mut ret = >::get_next_node_announcements(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, local__starting_point, _batch_amount); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(item)), is_owned: true } }); }; + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; local_ret.into() } extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_sync_routing_table(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, _init: &crate::lightning::ln::msgs::Init) { - >::sync_routing_table(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), unsafe { &*_init.inner }) + >::sync_routing_table(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), _init.get_native_ref()) } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_reply_channel_range(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::ReplyChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_channel_range(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_reply_short_channel_ids_end(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_query_channel_range(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_channel_range(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_query_short_channel_ids(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _msg: crate::lightning::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut ret = >::handle_query_short_channel_ids(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &_their_node_id.into_rust(), *unsafe { Box::from_raw(_msg.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).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::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } +use core::convert::Infallible as nativeInfallible; +impl From for crate::lightning::ln::wire::Type { + fn from(obj: nativeInfallible) -> Self { + unreachable!(); + } +} +impl From for crate::lightning::ln::wire::CustomMessageReader { + fn from(obj: nativeIgnoringMessageHandler) -> Self { + let mut rust_obj = IgnoringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = IgnoringMessageHandler_as_CustomMessageReader(&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 = core::ptr::null_mut(); + ret.free = Some(IgnoringMessageHandler_free_void); + ret + } +} +/// Constructs a new CustomMessageReader which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned CustomMessageReader must be freed before this_arg is +#[no_mangle] +pub extern "C" fn IgnoringMessageHandler_as_CustomMessageReader(this_arg: &IgnoringMessageHandler) -> crate::lightning::ln::wire::CustomMessageReader { + crate::lightning::ln::wire::CustomMessageReader { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + read: IgnoringMessageHandler_CustomMessageReader_read, + } +} + +#[must_use] +extern "C" fn IgnoringMessageHandler_CustomMessageReader_read(this_arg: *const c_void, mut _message_type: u16, mut _buffer: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_TypeZDecodeErrorZ { + let mut ret = >::read(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, _message_type, &mut _buffer.to_reader()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = if o.is_none() { crate::c_types::derived::COption_TypeZ::None } else { crate::c_types::derived::COption_TypeZ::Some( { Into::into(o.unwrap()) }) }; local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; + local_ret +} + +impl From for crate::lightning::ln::peer_handler::CustomMessageHandler { + fn from(obj: nativeIgnoringMessageHandler) -> Self { + let mut rust_obj = IgnoringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = IgnoringMessageHandler_as_CustomMessageHandler(&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 = core::ptr::null_mut(); + ret.free = Some(IgnoringMessageHandler_free_void); + ret + } +} +/// Constructs a new CustomMessageHandler which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned CustomMessageHandler must be freed before this_arg is +#[no_mangle] +pub extern "C" fn IgnoringMessageHandler_as_CustomMessageHandler(this_arg: &IgnoringMessageHandler) -> crate::lightning::ln::peer_handler::CustomMessageHandler { + crate::lightning::ln::peer_handler::CustomMessageHandler { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + handle_custom_message: IgnoringMessageHandler_CustomMessageHandler_handle_custom_message, + get_and_clear_pending_msg: IgnoringMessageHandler_CustomMessageHandler_get_and_clear_pending_msg, + CustomMessageReader: crate::lightning::ln::wire::CustomMessageReader { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + read: IgnoringMessageHandler_CustomMessageReader_read, + }, + } +} + +#[must_use] +extern "C" fn IgnoringMessageHandler_CustomMessageHandler_handle_custom_message(this_arg: *const c_void, mut msg: crate::lightning::ln::wire::Type, mut sender_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneLightningErrorZ { + unreachable!(); +} +#[must_use] +extern "C" fn IgnoringMessageHandler_CustomMessageHandler_get_and_clear_pending_msg(this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_PublicKeyTypeZZ { + let mut ret = >::get_and_clear_pending_msg(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, ); + 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) = item; let mut local_ret_0 = (crate::c_types::PublicKey::from_rust(&orig_ret_0_0), Into::into(orig_ret_0_1)).into(); local_ret_0 }); }; + local_ret.into() +} + use lightning::ln::peer_handler::ErroringMessageHandler as nativeErroringMessageHandlerImport; -type nativeErroringMessageHandler = nativeErroringMessageHandlerImport; +pub(crate) type nativeErroringMessageHandler = nativeErroringMessageHandlerImport; /// A dummy struct which implements `ChannelMessageHandler` without having any channels. /// You can provide one of these as the route_handler in a MessageHandler. @@ -221,7 +374,7 @@ pub struct ErroringMessageHandler { impl Drop for ErroringMessageHandler { fn drop(&mut self) { if self.is_owned && !<*mut nativeErroringMessageHandler>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -230,16 +383,22 @@ impl Drop for ErroringMessageHandler { pub extern "C" fn ErroringMessageHandler_free(this_obj: ErroringMessageHandler) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ErroringMessageHandler_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn ErroringMessageHandler_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeErroringMessageHandler); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ErroringMessageHandler { + pub(crate) fn get_native_ref(&self) -> &'static nativeErroringMessageHandler { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeErroringMessageHandler { + 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 nativeErroringMessageHandler { 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 } } @@ -248,15 +407,15 @@ impl ErroringMessageHandler { #[no_mangle] pub extern "C" fn ErroringMessageHandler_new() -> ErroringMessageHandler { let mut ret = lightning::ln::peer_handler::ErroringMessageHandler::new(); - ErroringMessageHandler { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ErroringMessageHandler { inner: ObjOps::heap_alloc(ret), is_owned: true } } impl From for crate::lightning::util::events::MessageSendEventsProvider { fn from(obj: nativeErroringMessageHandler) -> Self { - let mut rust_obj = ErroringMessageHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ErroringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ErroringMessageHandler_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(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(ErroringMessageHandler_free_void); ret } @@ -266,7 +425,7 @@ impl From for crate::lightning::util::events::Mess #[no_mangle] pub extern "C" fn ErroringMessageHandler_as_MessageSendEventsProvider(this_arg: &ErroringMessageHandler) -> crate::lightning::util::events::MessageSendEventsProvider { crate::lightning::util::events::MessageSendEventsProvider { - 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, get_and_clear_pending_msg_events: ErroringMessageHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, } @@ -281,10 +440,10 @@ extern "C" fn ErroringMessageHandler_MessageSendEventsProvider_get_and_clear_pen impl From for crate::lightning::ln::msgs::ChannelMessageHandler { fn from(obj: nativeErroringMessageHandler) -> Self { - let mut rust_obj = ErroringMessageHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ErroringMessageHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ErroringMessageHandler_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(); + rust_obj.inner = core::ptr::null_mut(); ret.free = Some(ErroringMessageHandler_free_void); ret } @@ -294,7 +453,7 @@ impl From for crate::lightning::ln::msgs::ChannelM #[no_mangle] pub extern "C" fn ErroringMessageHandler_as_ChannelMessageHandler(this_arg: &ErroringMessageHandler) -> 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: ErroringMessageHandler_ChannelMessageHandler_handle_open_channel, handle_accept_channel: ErroringMessageHandler_ChannelMessageHandler_handle_accept_channel, @@ -317,7 +476,7 @@ pub extern "C" fn ErroringMessageHandler_as_ChannelMessageHandler(this_arg: &Err handle_channel_update: ErroringMessageHandler_ChannelMessageHandler_handle_channel_update, handle_error: ErroringMessageHandler_ChannelMessageHandler_handle_error, MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider { - 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, get_and_clear_pending_msg_events: ErroringMessageHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, }, @@ -325,69 +484,69 @@ pub extern "C" fn ErroringMessageHandler_as_ChannelMessageHandler(this_arg: &Err } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(_their_features.take_inner()) }, unsafe { &*msg.inner }) + >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(_their_features.take_inner()) }, msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(_their_features.take_inner()) }, unsafe { &*msg.inner }) + >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(_their_features.take_inner()) }, msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_funding_locked(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingLocked) { - >::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*_their_features.inner }, unsafe { &*msg.inner }) + >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), _their_features.get_native_ref(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &their_node_id.into_rust(), unsafe { &*msg.inner }) + >::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &_their_node_id.into_rust(), unsafe { &*_msg.inner }) + >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &_their_node_id.into_rust(), _msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, mut _no_connection_possible: bool) { >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &_their_node_id.into_rust(), _no_connection_possible) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut _their_node_id: crate::c_types::PublicKey, _msg: &crate::lightning::ln::msgs::Init) { - >::peer_connected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &_their_node_id.into_rust(), unsafe { &*_msg.inner }) + >::peer_connected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &_their_node_id.into_rust(), _msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_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 nativeErroringMessageHandler) }, &_their_node_id.into_rust(), unsafe { &*_msg.inner }) + >::handle_error(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &_their_node_id.into_rust(), _msg.get_native_ref()) } use lightning::ln::peer_handler::MessageHandler as nativeMessageHandlerImport; -type nativeMessageHandler = nativeMessageHandlerImport; +pub(crate) type nativeMessageHandler = nativeMessageHandlerImport; /// Provides references to trait impls which handle different types of messages. #[must_use] @@ -408,7 +567,7 @@ pub struct MessageHandler { impl Drop for MessageHandler { fn drop(&mut self) { if self.is_owned && !<*mut nativeMessageHandler>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -417,53 +576,69 @@ impl Drop for MessageHandler { pub extern "C" fn MessageHandler_free(this_obj: MessageHandler) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn MessageHandler_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn MessageHandler_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMessageHandler); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl MessageHandler { + pub(crate) fn get_native_ref(&self) -> &'static nativeMessageHandler { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMessageHandler { + 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 nativeMessageHandler { 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 message handler which handles messages specific to channels. Usually this is just a -/// ChannelManager object or a ErroringMessageHandler. +/// [`ChannelManager`] object or an [`ErroringMessageHandler`]. +/// +/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager #[no_mangle] pub extern "C" fn MessageHandler_get_chan_handler(this_ptr: &MessageHandler) -> *const crate::lightning::ln::msgs::ChannelMessageHandler { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chan_handler; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chan_handler; inner_val } /// A message handler which handles messages specific to channels. Usually this is just a -/// ChannelManager object or a ErroringMessageHandler. +/// [`ChannelManager`] object or an [`ErroringMessageHandler`]. +/// +/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager #[no_mangle] pub extern "C" fn MessageHandler_set_chan_handler(this_ptr: &mut MessageHandler, mut val: crate::lightning::ln::msgs::ChannelMessageHandler) { - unsafe { &mut *this_ptr.inner }.chan_handler = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chan_handler = val; } /// A message handler which handles messages updating our knowledge of the network channel -/// graph. Usually this is just a NetGraphMsgHandlerMonitor object or an IgnoringMessageHandler. +/// graph. Usually this is just a [`NetGraphMsgHandler`] object or an +/// [`IgnoringMessageHandler`]. +/// +/// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler #[no_mangle] pub extern "C" fn MessageHandler_get_route_handler(this_ptr: &MessageHandler) -> *const crate::lightning::ln::msgs::RoutingMessageHandler { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.route_handler; + let mut inner_val = &mut this_ptr.get_native_mut_ref().route_handler; inner_val } /// A message handler which handles messages updating our knowledge of the network channel -/// graph. Usually this is just a NetGraphMsgHandlerMonitor object or an IgnoringMessageHandler. +/// graph. Usually this is just a [`NetGraphMsgHandler`] object or an +/// [`IgnoringMessageHandler`]. +/// +/// [`NetGraphMsgHandler`]: crate::routing::network_graph::NetGraphMsgHandler #[no_mangle] pub extern "C" fn MessageHandler_set_route_handler(this_ptr: &mut MessageHandler, mut val: crate::lightning::ln::msgs::RoutingMessageHandler) { - unsafe { &mut *this_ptr.inner }.route_handler = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.route_handler = val; } /// Constructs a new MessageHandler given each field #[must_use] #[no_mangle] pub extern "C" fn MessageHandler_new(mut chan_handler_arg: crate::lightning::ln::msgs::ChannelMessageHandler, mut route_handler_arg: crate::lightning::ln::msgs::RoutingMessageHandler) -> MessageHandler { - MessageHandler { inner: Box::into_raw(Box::new(nativeMessageHandler { + MessageHandler { inner: ObjOps::heap_alloc(nativeMessageHandler { chan_handler: chan_handler_arg, route_handler: route_handler_arg, - })), is_owned: true } + }), is_owned: true } } /// Provides an object which can be used to send data to and which uniquely identifies a connection /// to a remote host. You will need to be able to generate multiple of these which meet Eq and @@ -471,11 +646,12 @@ pub extern "C" fn MessageHandler_new(mut chan_handler_arg: crate::lightning::ln: /// /// For efficiency, Clone should be relatively cheap for this type. /// -/// You probably want to just extend an int and put a file descriptor in a struct and implement -/// send_data. Note that if you are using a higher-level net library that may call close() itself, -/// be careful to ensure you don't have races whereby you might register a new connection with an -/// fd which is the same as a previous one which has yet to be removed via -/// PeerManager::socket_disconnected(). +/// Two descriptors may compare equal (by [`cmp::Eq`] and [`hash::Hash`]) as long as the original +/// has been disconnected, the [`PeerManager`] has been informed of the disconnection (either by it +/// having triggered the disconnection or a call to [`PeerManager::socket_disconnected`]), and no +/// further calls to the [`PeerManager`] related to the original socket occur. This allows you to +/// use a file descriptor for your SocketDescriptor directly, however for simplicity you may wish +/// to simply use another value which is guaranteed to be globally unique instead. #[repr(C)] pub struct SocketDescriptor { /// An opaque pointer which is passed to your function implementations as an argument. @@ -484,58 +660,68 @@ pub struct SocketDescriptor { /// Attempts to send some data from the given slice to the peer. /// /// Returns the amount of data which was sent, possibly 0 if the socket has since disconnected. - /// Note that in the disconnected case, socket_disconnected must still fire and further write - /// attempts may occur until that time. + /// Note that in the disconnected case, [`PeerManager::socket_disconnected`] must still be + /// called and further write attempts may occur until that time. /// - /// If the returned size is smaller than data.len(), a write_available event must - /// trigger the next time more data can be written. Additionally, until the a send_data event - /// completes fully, no further read_events should trigger on the same peer! + /// If the returned size is smaller than `data.len()`, a + /// [`PeerManager::write_buffer_space_avail`] call must be made the next time more data can be + /// written. Additionally, until a `send_data` event completes fully, no further + /// [`PeerManager::read_event`] calls should be made for the same peer! Because this is to + /// prevent denial-of-service issues, you should not read or buffer any data from the socket + /// until then. /// - /// If a read_event on this descriptor had previously returned true (indicating that read - /// events should be paused to prevent DoS in the send buffer), resume_read may be set - /// indicating that read events on this descriptor should resume. A resume_read of false does - /// *not* imply that further read events should be paused. + /// If a [`PeerManager::read_event`] call on this descriptor had previously returned true + /// (indicating that read events should be paused to prevent DoS in the send buffer), + /// `resume_read` may be set indicating that read events on this descriptor should resume. A + /// `resume_read` of false carries no meaning, and should not cause any action. #[must_use] pub send_data: extern "C" fn (this_arg: *mut c_void, data: crate::c_types::u8slice, resume_read: bool) -> usize, - /// Disconnect the socket pointed to by this SocketDescriptor. Once this function returns, no - /// more calls to write_buffer_space_avail, read_event or socket_disconnected may be made with - /// this descriptor. No socket_disconnected call should be generated as a result of this call, - /// though races may occur whereby disconnect_socket is called after a call to - /// socket_disconnected but prior to socket_disconnected returning. + /// Disconnect the socket pointed to by this SocketDescriptor. + /// + /// You do *not* need to call [`PeerManager::socket_disconnected`] with this socket after this + /// call (doing so is a noop). pub disconnect_socket: extern "C" fn (this_arg: *mut c_void), /// Checks if two objects are equal given this object's this_arg pointer and another object. pub eq: extern "C" fn (this_arg: *const c_void, other_arg: &SocketDescriptor) -> bool, /// Calculate a succinct non-cryptographic hash for an object given its this_arg pointer. /// This is used, for example, for inclusion of this object in a hash map. pub hash: extern "C" fn (this_arg: *const c_void) -> u64, - /// Creates a copy of the object pointed to by this_arg, for a copy of this SocketDescriptor. - /// Note that the ultimate copy of the SocketDescriptor will have all function pointers the same as the original. - /// May be NULL if no action needs to be taken, the this_arg pointer will be copied into the new SocketDescriptor. - pub clone: Option *mut c_void>, + /// Called, if set, after this SocketDescriptor has been cloned into a duplicate object. + /// The new SocketDescriptor is provided, and should be mutated as needed to perform a + /// deep copy of the object pointed to by this_arg or avoid any double-freeing. + pub cloned: Option, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, } -impl std::cmp::Eq for SocketDescriptor {} -impl std::cmp::PartialEq for SocketDescriptor { - fn eq(&self, o: &Self) -> bool { (self.eq)(self.this_arg, o) } -} -impl std::hash::Hash for SocketDescriptor { - fn hash(&self, hasher: &mut H) { hasher.write_u64((self.hash)(self.this_arg)) } -} +unsafe impl Send for SocketDescriptor {} +unsafe impl Sync for SocketDescriptor {} #[no_mangle] -/// Creates a copy of a SocketDescriptor -pub extern "C" fn SocketDescriptor_clone(orig: &SocketDescriptor) -> SocketDescriptor { +pub(crate) extern "C" fn SocketDescriptor_clone_fields(orig: &SocketDescriptor) -> SocketDescriptor { SocketDescriptor { - this_arg: if let Some(f) = orig.clone { (f)(orig.this_arg) } else { orig.this_arg }, + this_arg: orig.this_arg, send_data: Clone::clone(&orig.send_data), disconnect_socket: Clone::clone(&orig.disconnect_socket), eq: Clone::clone(&orig.eq), hash: Clone::clone(&orig.hash), - clone: Clone::clone(&orig.clone), + cloned: Clone::clone(&orig.cloned), free: Clone::clone(&orig.free), } } +impl core::cmp::Eq for SocketDescriptor {} +impl core::cmp::PartialEq for SocketDescriptor { + fn eq(&self, o: &Self) -> bool { (self.eq)(self.this_arg, o) } +} +impl core::hash::Hash for SocketDescriptor { + fn hash(&self, hasher: &mut H) { hasher.write_u64((self.hash)(self.this_arg)) } +} +#[no_mangle] +/// Creates a copy of a SocketDescriptor +pub extern "C" fn SocketDescriptor_clone(orig: &SocketDescriptor) -> SocketDescriptor { + let mut res = SocketDescriptor_clone_fields(orig); + if let Some(f) = orig.cloned { (f)(&mut res) }; + res +} impl Clone for SocketDescriptor { fn clone(&self) -> Self { SocketDescriptor_clone(self) @@ -544,7 +730,7 @@ impl Clone for SocketDescriptor { use lightning::ln::peer_handler::SocketDescriptor as rustSocketDescriptor; impl rustSocketDescriptor for SocketDescriptor { - fn send_data(&mut self, data: &[u8], resume_read: bool) -> usize { + fn send_data(&mut self, mut data: &[u8], mut resume_read: bool) -> usize { let mut local_data = crate::c_types::u8slice::from_slice(data); let mut ret = (self.send_data)(self.this_arg, local_data, resume_read); ret @@ -556,7 +742,7 @@ impl rustSocketDescriptor for SocketDescriptor { // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl std::ops::Deref for SocketDescriptor { +impl core::ops::Deref for SocketDescriptor { type Target = Self; fn deref(&self) -> &Self { self @@ -574,7 +760,7 @@ impl Drop for SocketDescriptor { } use lightning::ln::peer_handler::PeerHandleError as nativePeerHandleErrorImport; -type nativePeerHandleError = nativePeerHandleErrorImport; +pub(crate) type nativePeerHandleError = nativePeerHandleErrorImport; /// Error for PeerManager errors. If you get one of these, you must disconnect the socket and /// generate no further read_event/write_buffer_space_avail/socket_disconnected calls for the @@ -597,7 +783,7 @@ pub struct PeerHandleError { impl Drop for PeerHandleError { fn drop(&mut self) { if self.is_owned && !<*mut nativePeerHandleError>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -606,16 +792,22 @@ impl Drop for PeerHandleError { pub extern "C" fn PeerHandleError_free(this_obj: PeerHandleError) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn PeerHandleError_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn PeerHandleError_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerHandleError); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PeerHandleError { + pub(crate) fn get_native_ref(&self) -> &'static nativePeerHandleError { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePeerHandleError { + 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 nativePeerHandleError { 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 } } @@ -623,28 +815,28 @@ impl PeerHandleError { /// we should go ahead and force-close any channels we have with it. #[no_mangle] pub extern "C" fn PeerHandleError_get_no_connection_possible(this_ptr: &PeerHandleError) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.no_connection_possible; + let mut inner_val = &mut this_ptr.get_native_mut_ref().no_connection_possible; *inner_val } /// Used to indicate that we probably can't make any future connections to this peer, implying /// we should go ahead and force-close any channels we have with it. #[no_mangle] pub extern "C" fn PeerHandleError_set_no_connection_possible(this_ptr: &mut PeerHandleError, mut val: bool) { - unsafe { &mut *this_ptr.inner }.no_connection_possible = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.no_connection_possible = val; } /// Constructs a new PeerHandleError given each field #[must_use] #[no_mangle] pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> PeerHandleError { - PeerHandleError { inner: Box::into_raw(Box::new(nativePeerHandleError { + PeerHandleError { inner: ObjOps::heap_alloc(nativePeerHandleError { no_connection_possible: no_connection_possible_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for PeerHandleError { fn clone(&self) -> Self { Self { - inner: if <*mut nativePeerHandleError>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + inner: if <*mut nativePeerHandleError>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -661,16 +853,27 @@ pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleErr } use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport; -type nativePeerManager = nativePeerManagerImport; +pub(crate) type nativePeerManager = nativePeerManagerImport; -/// A PeerManager manages a set of peers, described by their SocketDescriptor and marshalls socket -/// events into messages which it passes on to its MessageHandlers. +/// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls +/// socket events into messages which it passes on to its [`MessageHandler`]. +/// +/// Locks are taken internally, so you must never assume that reentrancy from a +/// [`SocketDescriptor`] call back into [`PeerManager`] methods will not deadlock. +/// +/// Calls to [`read_event`] will decode relevant messages and pass them to the +/// [`ChannelMessageHandler`], likely doing message processing in-line. Thus, the primary form of +/// parallelism in Rust-Lightning is in calls to [`read_event`]. Note, however, that calls to any +/// [`PeerManager`] functions related to the same connection must occur only in serial, making new +/// calls only after previous ones have returned. /// /// Rather than using a plain PeerManager, it is preferable to use either a SimpleArcPeerManager /// a SimpleRefPeerManager, for conciseness. See their documentation for more details, but /// essentially you should default to using a SimpleRefPeerManager, and use a /// SimpleArcPeerManager when you require a PeerManager with a static lifetime, such as when /// you're using lightning-net-tokio. +/// +/// [`read_event`]: PeerManager::read_event #[must_use] #[repr(C)] pub struct PeerManager { @@ -689,7 +892,7 @@ pub struct PeerManager { impl Drop for PeerManager { fn drop(&mut self) { if self.is_owned && !<*mut nativePeerManager>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -698,16 +901,22 @@ impl Drop for PeerManager { pub extern "C" fn PeerManager_free(this_obj: PeerManager) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn PeerManager_free_void(this_ptr: *mut c_void) { +pub(crate) extern "C" fn PeerManager_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePeerManager); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PeerManager { + pub(crate) fn get_native_ref(&self) -> &'static nativePeerManager { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePeerManager { + 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 nativePeerManager { 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 } } @@ -716,9 +925,9 @@ impl PeerManager { /// cryptographically secure random bytes. #[must_use] #[no_mangle] -pub extern "C" fn PeerManager_new(mut message_handler: crate::lightning::ln::peer_handler::MessageHandler, mut our_node_secret: crate::c_types::SecretKey, ephemeral_random_data: *const [u8; 32], mut logger: crate::lightning::util::logger::Logger) -> PeerManager { - let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger); - PeerManager { inner: Box::into_raw(Box::new(ret)), is_owned: true } +pub extern "C" fn PeerManager_new(mut message_handler: crate::lightning::ln::peer_handler::MessageHandler, mut our_node_secret: crate::c_types::SecretKey, ephemeral_random_data: *const [u8; 32], mut logger: crate::lightning::util::logger::Logger, mut custom_message_handler: crate::lightning::ln::peer_handler::CustomMessageHandler) -> PeerManager { + let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, our_node_secret.into_rust(), unsafe { &*ephemeral_random_data}, logger, custom_message_handler); + PeerManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Get the list of node ids for peers which have completed the initial handshake. @@ -729,7 +938,7 @@ pub extern "C" fn PeerManager_new(mut message_handler: crate::lightning::ln::pee #[must_use] #[no_mangle] pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate::c_types::derived::CVec_PublicKeyZ { - let mut ret = unsafe { &*this_arg.inner }.get_peer_node_ids(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_peer_node_ids(); let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); }; local_ret.into() } @@ -740,13 +949,15 @@ pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate /// /// Returns a small number of bytes to send to the remote node (currently always 50). /// -/// Panics if descriptor is duplicative with some other descriptor which has not yet had a -/// socket_disconnected(). +/// Panics if descriptor is duplicative with some other descriptor which has not yet been +/// [`socket_disconnected()`]. +/// +/// [`socket_disconnected()`]: PeerManager::socket_disconnected #[must_use] #[no_mangle] pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mut their_node_id: crate::c_types::PublicKey, mut descriptor: crate::lightning::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_CVec_u8ZPeerHandleErrorZ { - let mut ret = unsafe { &*this_arg.inner }.new_outbound_connection(their_node_id.into_rust(), descriptor); - 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( { item }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.new_outbound_connection(their_node_id.into_rust(), descriptor); + 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( { item }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -757,13 +968,15 @@ pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mu /// call socket_disconnected for the new descriptor but must disconnect the connection /// immediately. /// -/// Panics if descriptor is duplicative with some other descriptor which has not yet had -/// socket_disconnected called. +/// Panics if descriptor is duplicative with some other descriptor which has not yet been +/// [`socket_disconnected()`]. +/// +/// [`socket_disconnected()`]: PeerManager::socket_disconnected #[must_use] #[no_mangle] pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut descriptor: crate::lightning::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ { - let mut ret = unsafe { &*this_arg.inner }.new_inbound_connection(descriptor); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.new_inbound_connection(descriptor); + 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::peer_handler::PeerHandleError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -771,17 +984,19 @@ pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut /// /// May return an Err to indicate that the connection should be closed. /// -/// Will most likely call send_data on the descriptor passed in (or the descriptor handed into -/// new_*\\_connection) before returning. Thus, be very careful with reentrancy issues! The -/// invariants around calling write_buffer_space_avail in case a write did not fully complete -/// must still hold - be ready to call write_buffer_space_avail again if a write call generated -/// here isn't sufficient! Panics if the descriptor was not previously registered in a -/// new_\\*_connection event. +/// May call [`send_data`] on the descriptor passed in (or an equal descriptor) before +/// returning. Thus, be very careful with reentrancy issues! The invariants around calling +/// [`write_buffer_space_avail`] in case a write did not fully complete must still hold - be +/// ready to call `[write_buffer_space_avail`] again if a write call generated here isn't +/// sufficient! +/// +/// [`send_data`]: SocketDescriptor::send_data +/// [`write_buffer_space_avail`]: PeerManager::write_buffer_space_avail #[must_use] #[no_mangle] pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, descriptor: &mut crate::lightning::ln::peer_handler::SocketDescriptor) -> crate::c_types::derived::CResult_NonePeerHandleErrorZ { - let mut ret = unsafe { &*this_arg.inner }.write_buffer_space_avail(descriptor); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.write_buffer_space_avail(descriptor); + 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::peer_handler::PeerHandleError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -789,60 +1004,83 @@ pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, d /// /// May return an Err to indicate that the connection should be closed. /// -/// Will *not* call back into send_data on any descriptors to avoid reentrancy complexity. -/// Thus, however, you almost certainly want to call process_events() after any read_event to -/// generate send_data calls to handle responses. +/// Will *not* call back into [`send_data`] on any descriptors to avoid reentrancy complexity. +/// Thus, however, you should call [`process_events`] after any `read_event` to generate +/// [`send_data`] calls to handle responses. /// -/// If Ok(true) is returned, further read_events should not be triggered until a send_data call -/// on this file descriptor has resume_read set (preventing DoS issues in the send buffer). +/// If `Ok(true)` is returned, further read_events should not be triggered until a +/// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the +/// send buffer). /// -/// Panics if the descriptor was not previously registered in a new_*_connection event. +/// [`send_data`]: SocketDescriptor::send_data +/// [`process_events`]: PeerManager::process_events #[must_use] #[no_mangle] pub extern "C" fn PeerManager_read_event(this_arg: &PeerManager, peer_descriptor: &mut crate::lightning::ln::peer_handler::SocketDescriptor, mut data: crate::c_types::u8slice) -> crate::c_types::derived::CResult_boolPeerHandleErrorZ { - let mut ret = unsafe { &*this_arg.inner }.read_event(peer_descriptor, data.to_slice()); - 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::peer_handler::PeerHandleError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_event(peer_descriptor, data.to_slice()); + 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::peer_handler::PeerHandleError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } /// Checks for any events generated by our handlers and processes them. Includes sending most /// response messages as well as messages generated by calls to handler functions directly (eg -/// functions like ChannelManager::process_pending_htlc_forward or send_payment). +/// functions like [`ChannelManager::process_pending_htlc_forwards`] or [`send_payment`]). +/// +/// May call [`send_data`] on [`SocketDescriptor`]s. Thus, be very careful with reentrancy +/// issues! +/// +/// You don't have to call this function explicitly if you are using [`lightning-net-tokio`] +/// or one of the other clients provided in our language bindings. +/// +/// [`send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment +/// [`ChannelManager::process_pending_htlc_forwards`]: crate::ln::channelmanager::ChannelManager::process_pending_htlc_forwards +/// [`send_data`]: SocketDescriptor::send_data #[no_mangle] pub extern "C" fn PeerManager_process_events(this_arg: &PeerManager) { - unsafe { &*this_arg.inner }.process_events() + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_events() } /// Indicates that the given socket descriptor's connection is now closed. -/// -/// This must only be called if the socket has been disconnected by the peer or your own -/// decision to disconnect it and must NOT be called in any case where other parts of this -/// library (eg PeerHandleError, explicit disconnect_socket calls) instruct you to disconnect -/// the peer. -/// -/// Panics if the descriptor was not previously registered in a successful new_*_connection event. #[no_mangle] pub extern "C" fn PeerManager_socket_disconnected(this_arg: &PeerManager, descriptor: &crate::lightning::ln::peer_handler::SocketDescriptor) { - unsafe { &*this_arg.inner }.socket_disconnected(descriptor) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.socket_disconnected(descriptor) } /// Disconnect a peer given its node id. /// -/// Set no_connection_possible to true to prevent any further connection with this peer, +/// Set `no_connection_possible` to true to prevent any further connection with this peer, /// force-closing any channels we have with it. /// -/// If a peer is connected, this will call `disconnect_socket` on the descriptor for the peer, -/// so be careful about reentrancy issues. +/// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the +/// peer. Thus, be very careful about reentrancy issues. +/// +/// [`disconnect_socket`]: SocketDescriptor::disconnect_socket #[no_mangle] pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &PeerManager, mut node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - unsafe { &*this_arg.inner }.disconnect_by_node_id(node_id.into_rust(), no_connection_possible) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.disconnect_by_node_id(node_id.into_rust(), no_connection_possible) +} + +/// Disconnects all currently-connected peers. This is useful on platforms where there may be +/// an indication that TCP sockets have stalled even if we weren't around to time them out +/// using regular ping/pongs. +#[no_mangle] +pub extern "C" fn PeerManager_disconnect_all_peers(this_arg: &PeerManager) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.disconnect_all_peers() } -/// This function should be called roughly once every 30 seconds. -/// It will send pings to each peer and disconnect those which did not respond to the last round of pings. -/// Will most likely call send_data on all of the registered descriptors, thus, be very careful with reentrancy issues! +/// Send pings to each peer and disconnect those which did not respond to the last round of +/// pings. +/// +/// This may be called on any timescale you want, however, roughly once every five to ten +/// seconds is preferred. The call rate determines both how often we send a ping to our peers +/// and how much time they have to respond before we disconnect them. +/// +/// May call [`send_data`] on all [`SocketDescriptor`]s. Thus, be very careful with reentrancy +/// issues! +/// +/// [`send_data`]: SocketDescriptor::send_data #[no_mangle] pub extern "C" fn PeerManager_timer_tick_occurred(this_arg: &PeerManager) { - unsafe { &*this_arg.inner }.timer_tick_occurred() + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timer_tick_occurred() }