From: Matt Corallo Date: Wed, 18 Aug 2021 22:53:37 +0000 (+0000) Subject: Update auto-generated bindings X-Git-Tag: v0.0.101.1~2^2~2 X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-c-bindings;a=commitdiff_plain;h=696382c9fbc707aa5226f73910625136adb724fd Update auto-generated bindings --- diff --git a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs index 311c2f3..147889c 100644 --- a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs @@ -58,7 +58,7 @@ pub struct ChainMonitor { impl Drop for ChainMonitor { fn drop(&mut self) { if self.is_owned && !<*mut nativeChainMonitor>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -71,11 +71,17 @@ extern "C" fn ChainMonitor_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainMonitor); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChainMonitor { + pub(crate) fn get_native_ref(&self) -> &'static nativeChainMonitor { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainMonitor { + 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 nativeChainMonitor { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -94,12 +100,12 @@ impl ChainMonitor { pub extern "C" fn ChainMonitor_new(chain_source: *mut crate::lightning::chain::Filter, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut feeest: crate::lightning::chain::chaininterface::FeeEstimator, mut persister: crate::lightning::chain::channelmonitor::Persist) -> ChainMonitor { let mut local_chain_source = if chain_source == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_source) } }) }; let mut ret = lightning::chain::chainmonitor::ChainMonitor::new(local_chain_source, broadcaster, logger, feeest, persister); - ChainMonitor { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ChainMonitor { inner: ObjOps::heap_alloc(ret), is_owned: true } } impl From for crate::lightning::chain::Listen { fn from(obj: nativeChainMonitor) -> Self { - let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChainMonitor_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(); @@ -112,7 +118,7 @@ impl From for crate::lightning::chain::Listen { #[no_mangle] pub extern "C" fn ChainMonitor_as_Listen(this_arg: &ChainMonitor) -> 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, block_connected: ChainMonitor_Listen_block_connected, block_disconnected: ChainMonitor_Listen_block_disconnected, @@ -128,7 +134,7 @@ extern "C" fn ChainMonitor_Listen_block_disconnected(this_arg: *const c_void, he impl From for crate::lightning::chain::Confirm { fn from(obj: nativeChainMonitor) -> Self { - let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChainMonitor_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(); @@ -141,7 +147,7 @@ impl From for crate::lightning::chain::Confirm { #[no_mangle] pub extern "C" fn ChainMonitor_as_Confirm(this_arg: &ChainMonitor) -> 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: ChainMonitor_Confirm_transactions_confirmed, transaction_unconfirmed: ChainMonitor_Confirm_transaction_unconfirmed, @@ -169,7 +175,7 @@ extern "C" fn ChainMonitor_Confirm_get_relevant_txids(this_arg: *const c_void) - impl From for crate::lightning::chain::Watch { fn from(obj: nativeChainMonitor) -> Self { - let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChainMonitor_as_Watch(&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(); @@ -182,7 +188,7 @@ impl From for crate::lightning::chain::Watch { #[no_mangle] pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::lightning::chain::Watch { crate::lightning::chain::Watch { - 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, watch_channel: ChainMonitor_Watch_watch_channel, update_channel: ChainMonitor_Watch_update_channel, @@ -211,7 +217,7 @@ extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const impl From for crate::lightning::util::events::EventsProvider { fn from(obj: nativeChainMonitor) -> Self { - let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = ChainMonitor_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(); @@ -224,7 +230,7 @@ impl From for crate::lightning::util::events::EventsProvider #[no_mangle] pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::lightning::util::events::EventsProvider { crate::lightning::util::events::EventsProvider { - 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, process_pending_events: ChainMonitor_EventsProvider_process_pending_events, } diff --git a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs index 1161216..ff5043f 100644 --- a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs @@ -48,7 +48,7 @@ pub struct ChannelMonitorUpdate { impl Drop for ChannelMonitorUpdate { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -61,11 +61,17 @@ extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelMonitorUpdate { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitorUpdate { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitorUpdate { + 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 nativeChannelMonitorUpdate { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -83,7 +89,7 @@ impl ChannelMonitorUpdate { /// its docs for more details. #[no_mangle] pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().update_id; *inner_val } /// The sequence number of this update. Updates *must* be replayed in-order according to this @@ -99,13 +105,13 @@ pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUp /// its docs for more details. #[no_mangle] pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) { - unsafe { &mut *this_ptr.inner }.update_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_id = val; } impl Clone for ChannelMonitorUpdate { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -133,7 +139,7 @@ pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLO #[no_mangle] /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -143,7 +149,7 @@ pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// An error enum representing a failure to persist a channel monitor update. @@ -279,7 +285,7 @@ pub struct MonitorUpdateError { impl Drop for MonitorUpdateError { fn drop(&mut self) { if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -292,11 +298,17 @@ extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl MonitorUpdateError { + pub(crate) fn get_native_ref(&self) -> &'static nativeMonitorUpdateError { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMonitorUpdateError { + 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 nativeMonitorUpdateError { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -305,7 +317,7 @@ impl Clone for MonitorUpdateError { fn clone(&self) -> Self { Self { inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -370,13 +382,13 @@ impl MonitorEvent { nativeMonitorEvent::HTLCEvent (ref a, ) => { let mut a_nonref = (*a).clone(); MonitorEvent::HTLCEvent ( - crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, + crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, ) }, nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => { let mut a_nonref = (*a).clone(); MonitorEvent::CommitmentTxBroadcasted ( - crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, + crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, ) }, } @@ -386,12 +398,12 @@ impl MonitorEvent { match native { nativeMonitorEvent::HTLCEvent (mut a, ) => { MonitorEvent::HTLCEvent ( - crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true }, + crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a), is_owned: true }, ) }, nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => { MonitorEvent::CommitmentTxBroadcasted ( - crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true }, + crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a), is_owned: true }, ) }, } @@ -440,7 +452,7 @@ pub struct HTLCUpdate { impl Drop for HTLCUpdate { fn drop(&mut self) { if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -453,11 +465,17 @@ extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl HTLCUpdate { + pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCUpdate { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCUpdate { + 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 nativeHTLCUpdate { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -466,7 +484,7 @@ impl Clone for HTLCUpdate { fn clone(&self) -> Self { Self { inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -484,7 +502,7 @@ pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate { #[no_mangle] /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -494,7 +512,7 @@ pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_t /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound @@ -540,7 +558,7 @@ pub struct ChannelMonitor { impl Drop for ChannelMonitor { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -553,11 +571,17 @@ extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelMonitor { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitor { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitor { + 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 nativeChannelMonitor { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -565,7 +589,7 @@ impl ChannelMonitor { #[no_mangle] /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -578,8 +602,8 @@ pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate: #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ { - let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger); - 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::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_monitor(updates.get_native_ref(), broadcaster, fee_estimator, logger); + 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::chain::channelmonitor::MonitorUpdateError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -588,7 +612,7 @@ pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updat #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.get_latest_update_id(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_update_id(); ret } @@ -596,8 +620,8 @@ pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ { - let mut ret = unsafe { &*this_arg.inner }.get_funding_txo(); - let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, orig_ret_1.into_bytes().into()).into(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_funding_txo(); + let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(orig_ret_0), is_owned: true }, orig_ret_1.into_bytes().into()).into(); local_ret } @@ -606,7 +630,7 @@ pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> c #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ { - let mut ret = unsafe { &*this_arg.inner }.get_outputs_to_watch(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_outputs_to_watch(); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, orig_orig_ret_0_1_0_1.into_bytes().into()).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); }; local_ret.into() } @@ -616,7 +640,7 @@ pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) /// have been registered. #[no_mangle] pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor, filter: &crate::lightning::chain::Filter) { - unsafe { &*this_arg.inner }.load_outputs_to_watch(filter) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.load_outputs_to_watch(filter) } /// Get the list of HTLCs who's status has been updated on chain. This should be called by @@ -624,7 +648,7 @@ pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ { - let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_monitor_events(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_monitor_events(); let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); }; local_ret.into() } @@ -638,7 +662,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ { - let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_events(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_events(); let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::Event::native_into(item) }); }; local_ret.into() } @@ -655,7 +679,7 @@ pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &Channel #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &ChannelMonitor, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ { - let mut ret = unsafe { &*this_arg.inner }.get_latest_holder_commitment_txn(logger); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_holder_commitment_txn(logger); let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::Transaction::from_bitcoin(&item) }); }; local_ret.into() } @@ -675,7 +699,7 @@ pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &Cha #[no_mangle] pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ { 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 }); }; - let mut ret = unsafe { &*this_arg.inner }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height, broadcaster, fee_estimator, logger); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height, broadcaster, fee_estimator, logger); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); }; local_ret.into() } @@ -684,7 +708,7 @@ pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, head /// appropriately. #[no_mangle] pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) { - unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger) } /// Processes transactions confirmed in a block with the given header and height, returning new @@ -698,7 +722,7 @@ pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, h #[no_mangle] pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ { 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 }); }; - let mut ret = unsafe { &*this_arg.inner }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height, broadcaster, fee_estimator, logger); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::>()[..], height, broadcaster, fee_estimator, logger); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); }; local_ret.into() } @@ -711,7 +735,7 @@ pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &ChannelMonito /// [`block_disconnected`]: Self::block_disconnected #[no_mangle] pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &ChannelMonitor, txid: *const [u8; 32], mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) { - unsafe { &*this_arg.inner }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger) } /// Updates the monitor with the current best chain tip, returning new outputs to watch. See @@ -724,7 +748,7 @@ pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &ChannelMonit #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ { - let mut ret = unsafe { &*this_arg.inner }.best_block_updated(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.best_block_updated(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { let (mut orig_orig_ret_0_1_0_0, mut orig_orig_ret_0_1_0_1) = item; let mut local_orig_ret_0_1_0 = (orig_orig_ret_0_1_0_0, crate::c_types::TxOut::from_rust(orig_orig_ret_0_1_0_1)).into(); local_orig_ret_0_1_0 }); }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1.into()).into(); local_ret_0 }); }; local_ret.into() } @@ -733,7 +757,7 @@ pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &ChannelMonitor, h #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_TxidZ { - let mut ret = unsafe { &*this_arg.inner }.get_relevant_txids(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_relevant_txids(); let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); }; local_ret.into() } @@ -743,8 +767,8 @@ pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) - #[must_use] #[no_mangle] pub extern "C" fn ChannelMonitor_current_best_block(this_arg: &ChannelMonitor) -> 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 } + 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 } } /// `Persist` defines behavior for persisting channel monitors: this could mean @@ -816,12 +840,12 @@ pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist { use lightning::chain::channelmonitor::Persist as rustPersist; impl rustPersist for Persist { fn persist_new_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { - let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false }); 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(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } fn update_persisted_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, mut data: &lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { - let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const _) as *mut _) }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false }); 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(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } @@ -850,6 +874,6 @@ impl Drop for Persist { pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ { let arg_conv = arg; let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor), 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::chain::channelmonitor::ChannelMonitor { 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 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::chain::channelmonitor::ChannelMonitor { 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 { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/chain/keysinterface.rs b/lightning-c-bindings/src/lightning/chain/keysinterface.rs index 1f542b4..ed6df19 100644 --- a/lightning-c-bindings/src/lightning/chain/keysinterface.rs +++ b/lightning-c-bindings/src/lightning/chain/keysinterface.rs @@ -39,7 +39,7 @@ pub struct DelayedPaymentOutputDescriptor { impl Drop for DelayedPaymentOutputDescriptor { fn drop(&mut self) { if self.is_owned && !<*mut nativeDelayedPaymentOutputDescriptor>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -52,11 +52,17 @@ extern "C" fn DelayedPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDelayedPaymentOutputDescriptor); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl DelayedPaymentOutputDescriptor { + pub(crate) fn get_native_ref(&self) -> &'static nativeDelayedPaymentOutputDescriptor { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDelayedPaymentOutputDescriptor { + 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 nativeDelayedPaymentOutputDescriptor { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -64,62 +70,62 @@ impl DelayedPaymentOutputDescriptor { /// The outpoint which is spendable #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_outpoint(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::lightning::chain::transaction::OutPoint { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint; - crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint; + crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The outpoint which is spendable #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_outpoint(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::lightning::chain::transaction::OutPoint) { - unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; } /// Per commitment point to derive delayed_payment_key by key holder #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_per_commitment_point(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// Per commitment point to derive delayed_payment_key by key holder #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_per_commitment_point(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.per_commitment_point = val.into_rust(); } /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in /// the witness_script. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_to_self_delay(this_ptr: &DelayedPaymentOutputDescriptor) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.to_self_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().to_self_delay; *inner_val } /// The nSequence value which must be set in the spending input to satisfy the OP_CSV in /// the witness_script. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_to_self_delay(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u16) { - unsafe { &mut *this_ptr.inner }.to_self_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.to_self_delay = val; } /// The output which is referenced by the given outpoint #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_output(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::TxOut) { - unsafe { &mut *this_ptr.inner }.output = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.output = val.into_rust(); } /// The revocation point specific to the commitment transaction which was broadcast. Used to /// derive the witnessScript for this output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_revocation_pubkey(this_ptr: &DelayedPaymentOutputDescriptor) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_pubkey; crate::c_types::PublicKey::from_rust(&inner_val) } /// The revocation point specific to the commitment transaction which was broadcast. Used to /// derive the witnessScript for this output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_revocation_pubkey(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.revocation_pubkey = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_pubkey = val.into_rust(); } /// Arbitrary identification information returned by a call to /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in /// the channel to spend the output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &DelayedPaymentOutputDescriptor) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id; inner_val } /// Arbitrary identification information returned by a call to @@ -127,24 +133,24 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: & /// the channel to spend the output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_keys_id = val.data; } /// The value of the channel which this output originated from, possibly indirectly. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &DelayedPaymentOutputDescriptor) -> 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 of the channel which this output originated from, possibly indirectly. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: u64) { - unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val; } /// Constructs a new DelayedPaymentOutputDescriptor given each field #[must_use] #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_new(mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut per_commitment_point_arg: crate::c_types::PublicKey, mut to_self_delay_arg: u16, mut output_arg: crate::c_types::TxOut, mut revocation_pubkey_arg: crate::c_types::PublicKey, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> DelayedPaymentOutputDescriptor { - DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeDelayedPaymentOutputDescriptor { + DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(nativeDelayedPaymentOutputDescriptor { outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) }, per_commitment_point: per_commitment_point_arg.into_rust(), to_self_delay: to_self_delay_arg, @@ -152,13 +158,13 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_new(mut outpoint_arg: crate::li revocation_pubkey: revocation_pubkey_arg.into_rust(), channel_keys_id: channel_keys_id_arg.data, channel_value_satoshis: channel_value_satoshis_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for DelayedPaymentOutputDescriptor { fn clone(&self) -> Self { Self { inner: if <*mut nativeDelayedPaymentOutputDescriptor>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -176,7 +182,7 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_clone(orig: &DelayedPaymentOutp #[no_mangle] /// Serialize the DelayedPaymentOutputDescriptor object into a byte array which can be read by DelayedPaymentOutputDescriptor_read pub extern "C" fn DelayedPaymentOutputDescriptor_write(obj: &DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn DelayedPaymentOutputDescriptor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -186,7 +192,7 @@ pub(crate) extern "C" fn DelayedPaymentOutputDescriptor_write_void(obj: *const c /// Read a DelayedPaymentOutputDescriptor from a byte array, created by DelayedPaymentOutputDescriptor_write pub extern "C" fn DelayedPaymentOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_DelayedPaymentOutputDescriptorDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -213,7 +219,7 @@ pub struct StaticPaymentOutputDescriptor { impl Drop for StaticPaymentOutputDescriptor { fn drop(&mut self) { if self.is_owned && !<*mut nativeStaticPaymentOutputDescriptor>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -226,11 +232,17 @@ extern "C" fn StaticPaymentOutputDescriptor_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeStaticPaymentOutputDescriptor); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl StaticPaymentOutputDescriptor { + pub(crate) fn get_native_ref(&self) -> &'static nativeStaticPaymentOutputDescriptor { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeStaticPaymentOutputDescriptor { + 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 nativeStaticPaymentOutputDescriptor { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -238,25 +250,25 @@ impl StaticPaymentOutputDescriptor { /// The outpoint which is spendable #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_get_outpoint(this_ptr: &StaticPaymentOutputDescriptor) -> crate::lightning::chain::transaction::OutPoint { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint; - crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint; + crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The outpoint which is spendable #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_set_outpoint(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::lightning::chain::transaction::OutPoint) { - unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; } /// The output which is referenced by the given outpoint #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_set_output(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::TxOut) { - unsafe { &mut *this_ptr.inner }.output = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.output = val.into_rust(); } /// Arbitrary identification information returned by a call to /// `Sign::channel_keys_id()`. This may be useful in re-deriving keys used in /// the channel to spend the output. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &StaticPaymentOutputDescriptor) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_keys_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id; inner_val } /// Arbitrary identification information returned by a call to @@ -264,35 +276,35 @@ pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &S /// the channel to spend the output. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.channel_keys_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_keys_id = val.data; } /// The value of the channel which this transactions spends. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_value_satoshis(this_ptr: &StaticPaymentOutputDescriptor) -> 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 of the channel which this transactions spends. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_value_satoshis(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: u64) { - unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_value_satoshis = val; } /// Constructs a new StaticPaymentOutputDescriptor given each field #[must_use] #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_new(mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut output_arg: crate::c_types::TxOut, mut channel_keys_id_arg: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis_arg: u64) -> StaticPaymentOutputDescriptor { - StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(nativeStaticPaymentOutputDescriptor { + StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(nativeStaticPaymentOutputDescriptor { outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) }, output: output_arg.into_rust(), channel_keys_id: channel_keys_id_arg.data, channel_value_satoshis: channel_value_satoshis_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for StaticPaymentOutputDescriptor { fn clone(&self) -> Self { Self { inner: if <*mut nativeStaticPaymentOutputDescriptor>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -310,7 +322,7 @@ pub extern "C" fn StaticPaymentOutputDescriptor_clone(orig: &StaticPaymentOutput #[no_mangle] /// Serialize the StaticPaymentOutputDescriptor object into a byte array which can be read by StaticPaymentOutputDescriptor_read pub extern "C" fn StaticPaymentOutputDescriptor_write(obj: &StaticPaymentOutputDescriptor) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn StaticPaymentOutputDescriptor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -320,7 +332,7 @@ pub(crate) extern "C" fn StaticPaymentOutputDescriptor_write_void(obj: *const c_ /// Read a StaticPaymentOutputDescriptor from a byte array, created by StaticPaymentOutputDescriptor_write pub extern "C" fn StaticPaymentOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_StaticPaymentOutputDescriptorDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// When on-chain outputs are created by rust-lightning (which our counterparty is not able to @@ -436,20 +448,20 @@ impl SpendableOutputDescriptor { let mut outpoint_nonref = (*outpoint).clone(); let mut output_nonref = (*output).clone(); SpendableOutputDescriptor::StaticOutput { - outpoint: crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint_nonref)), is_owned: true }, + outpoint: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(outpoint_nonref), is_owned: true }, output: crate::c_types::TxOut::from_rust(output_nonref), } }, nativeSpendableOutputDescriptor::DelayedPaymentOutput (ref a, ) => { let mut a_nonref = (*a).clone(); SpendableOutputDescriptor::DelayedPaymentOutput ( - crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, + crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, ) }, nativeSpendableOutputDescriptor::StaticPaymentOutput (ref a, ) => { let mut a_nonref = (*a).clone(); SpendableOutputDescriptor::StaticPaymentOutput ( - crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true }, + crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, ) }, } @@ -459,18 +471,18 @@ impl SpendableOutputDescriptor { match native { nativeSpendableOutputDescriptor::StaticOutput {mut outpoint, mut output, } => { SpendableOutputDescriptor::StaticOutput { - outpoint: crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(outpoint)), is_owned: true }, + outpoint: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(outpoint), is_owned: true }, output: crate::c_types::TxOut::from_rust(output), } }, nativeSpendableOutputDescriptor::DelayedPaymentOutput (mut a, ) => { SpendableOutputDescriptor::DelayedPaymentOutput ( - crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true }, + crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a), is_owned: true }, ) }, nativeSpendableOutputDescriptor::StaticPaymentOutput (mut a, ) => { SpendableOutputDescriptor::StaticPaymentOutput ( - crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: Box::into_raw(Box::new(a)), is_owned: true }, + crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor { inner: ObjOps::heap_alloc(a), is_owned: true }, ) }, } @@ -511,7 +523,7 @@ pub extern "C" fn SpendableOutputDescriptor_write(obj: &SpendableOutputDescripto /// Read a SpendableOutputDescriptor from a byte array, created by SpendableOutputDescriptor_write pub extern "C" fn SpendableOutputDescriptor_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SpendableOutputDescriptorDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// A trait to sign lightning channel transactions as described in BOLT 3. @@ -700,19 +712,19 @@ impl rustBaseSign for BaseSign { if let Some(f) = self.set_pubkeys { (f)(&self); } - unsafe { &*self.pubkeys.inner } + self.pubkeys.get_native_ref() } fn channel_keys_id(&self) -> [u8; 32] { let mut ret = (self.channel_keys_id)(self.this_arg); ret.data } fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { - let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { - let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -722,12 +734,12 @@ impl rustBaseSign for BaseSign { local_ret } fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.sign_justice_revoked_htlc)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.sign_justice_revoked_htlc)(self.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::key::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -737,12 +749,12 @@ impl rustBaseSign for BaseSign { local_ret } fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { - (self.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false }) + (self.ready_channel)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const _) as *mut _) }, is_owned: false }) } } @@ -811,19 +823,19 @@ impl lightning::chain::keysinterface::BaseSign for Sign { if let Some(f) = self.BaseSign.set_pubkeys { (f)(&self.BaseSign); } - unsafe { &*self.BaseSign.pubkeys.inner } + self.BaseSign.pubkeys.get_native_ref() } fn channel_keys_id(&self) -> [u8; 32] { let mut ret = (self.BaseSign.channel_keys_id)(self.BaseSign.this_arg); ret.data } fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { - let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::Signature, Vec), ()> { - let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { (commitment_tx as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -833,12 +845,12 @@ impl lightning::chain::keysinterface::BaseSign for Sign { local_ret } fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::key::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::key::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { (htlc as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -848,12 +860,12 @@ impl lightning::chain::keysinterface::BaseSign for Sign { local_ret } fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn ready_channel(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { - (self.BaseSign.ready_channel)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { (channel_parameters as *const _) as *mut _ }, is_owned: false }) + (self.BaseSign.ready_channel)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const _) as *mut _) }, is_owned: false }) } } impl lightning::util::ser::Writeable for Sign { @@ -1049,7 +1061,7 @@ pub struct InMemorySigner { impl Drop for InMemorySigner { fn drop(&mut self) { if self.is_owned && !<*mut nativeInMemorySigner>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1062,11 +1074,17 @@ extern "C" fn InMemorySigner_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInMemorySigner); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InMemorySigner { + pub(crate) fn get_native_ref(&self) -> &'static nativeInMemorySigner { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInMemorySigner { + 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 nativeInMemorySigner { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1074,74 +1092,74 @@ impl InMemorySigner { /// Private key of anchor tx #[no_mangle] pub extern "C" fn InMemorySigner_get_funding_key(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_key; inner_val.as_ref() } /// Private key of anchor tx #[no_mangle] pub extern "C" fn InMemorySigner_set_funding_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) { - unsafe { &mut *this_ptr.inner }.funding_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_key = val.into_rust(); } /// Holder secret key for blinded revocation pubkey #[no_mangle] pub extern "C" fn InMemorySigner_get_revocation_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_base_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_base_key; inner_val.as_ref() } /// Holder secret key for blinded revocation pubkey #[no_mangle] pub extern "C" fn InMemorySigner_set_revocation_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) { - unsafe { &mut *this_ptr.inner }.revocation_base_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_base_key = val.into_rust(); } /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions #[no_mangle] pub extern "C" fn InMemorySigner_get_payment_key(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_key; inner_val.as_ref() } /// Holder secret key used for our balance in counterparty-broadcasted commitment transactions #[no_mangle] pub extern "C" fn InMemorySigner_set_payment_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) { - unsafe { &mut *this_ptr.inner }.payment_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_key = val.into_rust(); } /// Holder secret key used in HTLC tx #[no_mangle] pub extern "C" fn InMemorySigner_get_delayed_payment_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_base_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_base_key; inner_val.as_ref() } /// Holder secret key used in HTLC tx #[no_mangle] pub extern "C" fn InMemorySigner_set_delayed_payment_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) { - unsafe { &mut *this_ptr.inner }.delayed_payment_base_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_base_key = val.into_rust(); } /// Holder htlc secret key used in commitment tx htlc outputs #[no_mangle] pub extern "C" fn InMemorySigner_get_htlc_base_key(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_base_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_base_key; inner_val.as_ref() } /// Holder htlc secret key used in commitment tx htlc outputs #[no_mangle] pub extern "C" fn InMemorySigner_set_htlc_base_key(this_ptr: &mut InMemorySigner, mut val: crate::c_types::SecretKey) { - unsafe { &mut *this_ptr.inner }.htlc_base_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_base_key = val.into_rust(); } /// Commitment seed #[no_mangle] pub extern "C" fn InMemorySigner_get_commitment_seed(this_ptr: &InMemorySigner) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_seed; + let mut inner_val = &mut this_ptr.get_native_mut_ref().commitment_seed; inner_val } /// Commitment seed #[no_mangle] pub extern "C" fn InMemorySigner_set_commitment_seed(this_ptr: &mut InMemorySigner, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.commitment_seed = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commitment_seed = val.data; } impl Clone for InMemorySigner { fn clone(&self) -> Self { Self { inner: if <*mut nativeInMemorySigner>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1161,7 +1179,7 @@ pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner #[no_mangle] pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::InMemorySigner { let mut ret = lightning::chain::keysinterface::InMemorySigner::new(secp256k1::SECP256K1, funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data); - crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Counterparty pubkeys. @@ -1169,8 +1187,8 @@ pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut ret = unsafe { &*this_arg.inner }.counterparty_pubkeys(); - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.counterparty_pubkeys(); + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// The contest_delay value specified by our counterparty and applied on holder-broadcastable @@ -1180,7 +1198,7 @@ pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &InMemorySigner) #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &InMemorySigner) -> u16 { - let mut ret = unsafe { &*this_arg.inner }.counterparty_selected_contest_delay(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.counterparty_selected_contest_delay(); ret } @@ -1191,7 +1209,7 @@ pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: & #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemorySigner) -> u16 { - let mut ret = unsafe { &*this_arg.inner }.holder_selected_contest_delay(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.holder_selected_contest_delay(); ret } @@ -1200,7 +1218,7 @@ pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &InMemo #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool { - let mut ret = unsafe { &*this_arg.inner }.is_outbound(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_outbound(); ret } @@ -1209,8 +1227,8 @@ pub extern "C" fn InMemorySigner_is_outbound(this_arg: &InMemorySigner) -> bool #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) -> crate::lightning::chain::transaction::OutPoint { - let mut ret = unsafe { &*this_arg.inner }.funding_outpoint(); - crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_outpoint(); + crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Obtain a ChannelTransactionParameters for this channel, to be used when verifying or @@ -1220,8 +1238,8 @@ pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &InMemorySigner) -> #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelTransactionParameters { - let mut ret = unsafe { &*this_arg.inner }.get_channel_parameters(); - crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_channel_parameters(); + crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Sign the single input of spend_tx at index `input_idx` which spends the output @@ -1232,7 +1250,7 @@ pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &InMemorySigne #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::StaticPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ { - let mut ret = unsafe { &*this_arg.inner }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign_counterparty_payment_input(&spend_tx.into_bitcoin(), input_idx, descriptor.get_native_ref(), secp256k1::SECP256K1); 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 local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1246,14 +1264,14 @@ pub extern "C" fn InMemorySigner_sign_counterparty_payment_input(this_arg: &InMe #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &InMemorySigner, mut spend_tx: crate::c_types::Transaction, mut input_idx: usize, descriptor: &crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor) -> crate::c_types::derived::CResult_CVec_CVec_u8ZZNoneZ { - let mut ret = unsafe { &*this_arg.inner }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, unsafe { &*descriptor.inner }, secp256k1::SECP256K1); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign_dynamic_p2wsh_input(&spend_tx.into_bitcoin(), input_idx, descriptor.get_native_ref(), secp256k1::SECP256K1); 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 local_ret_0_0 = Vec::new(); for mut item in item.drain(..) { local_ret_0_0.push( { item }); }; local_ret_0_0.into() }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } impl From for crate::lightning::chain::keysinterface::BaseSign { fn from(obj: nativeInMemorySigner) -> Self { - let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = InMemorySigner_as_BaseSign(&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(); @@ -1266,7 +1284,7 @@ impl From for crate::lightning::chain::keysinterface::Base #[no_mangle] pub extern "C" fn InMemorySigner_as_BaseSign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::BaseSign { crate::lightning::chain::keysinterface::BaseSign { - 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_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point, release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret, @@ -1298,7 +1316,7 @@ extern "C" fn InMemorySigner_BaseSign_release_commitment_secret(this_arg: *const #[must_use] extern "C" fn InMemorySigner_BaseSign_pubkeys(this_arg: *const c_void) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { let mut ret = >::pubkeys(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, ); - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } extern "C" fn InMemorySigner_BaseSign_set_pubkeys(trait_self_arg: &BaseSign) { // This is a bit race-y in the general case, but for our specific use-cases today, we're safe @@ -1314,13 +1332,13 @@ extern "C" fn InMemorySigner_BaseSign_channel_keys_id(this_arg: *const c_void) - } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::CommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { - let mut ret = >::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1); + let mut ret = >::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::SECP256K1); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { - let mut ret = >::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*commitment_tx.inner }, secp256k1::SECP256K1); + let mut ret = >::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::SECP256K1); 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_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1332,13 +1350,13 @@ extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_output(this_arg: *con } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_htlc(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), unsafe { &*htlc.inner }, secp256k1::SECP256K1); + let mut ret = >::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), htlc.get_native_ref(), secp256k1::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), unsafe { &*htlc.inner }, secp256k1::SECP256K1); + let mut ret = >::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), htlc.get_native_ref(), secp256k1::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1350,17 +1368,17 @@ extern "C" fn InMemorySigner_BaseSign_sign_closing_transaction(this_arg: *const } #[must_use] extern "C" fn InMemorySigner_BaseSign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*msg.inner }, secp256k1::SECP256K1); + let mut ret = >::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, msg.get_native_ref(), secp256k1::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } extern "C" fn InMemorySigner_BaseSign_ready_channel(this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters) { - >::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, unsafe { &*channel_parameters.inner }) + >::ready_channel(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, channel_parameters.get_native_ref()) } impl From for crate::lightning::chain::keysinterface::Sign { fn from(obj: nativeInMemorySigner) -> Self { - let mut rust_obj = InMemorySigner { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = InMemorySigner_as_Sign(&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(); @@ -1373,10 +1391,10 @@ impl From for crate::lightning::chain::keysinterface::Sign #[no_mangle] pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::Sign { crate::lightning::chain::keysinterface::Sign { - 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, BaseSign: crate::lightning::chain::keysinterface::BaseSign { - 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_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point, release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret, @@ -1408,7 +1426,7 @@ extern "C" fn Sign_InMemorySigner_cloned(new_obj: &mut crate::lightning::chain:: #[no_mangle] /// Serialize the InMemorySigner object into a byte array which can be read by InMemorySigner_read pub extern "C" fn InMemorySigner_write(obj: &InMemorySigner) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1418,7 +1436,7 @@ pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate: /// Read a InMemorySigner from a byte array, created by InMemorySigner_write pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -1450,7 +1468,7 @@ pub struct KeysManager { impl Drop for KeysManager { fn drop(&mut self) { if self.is_owned && !<*mut nativeKeysManager>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1463,11 +1481,17 @@ extern "C" fn KeysManager_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeKeysManager); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl KeysManager { + pub(crate) fn get_native_ref(&self) -> &'static nativeKeysManager { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeKeysManager { + 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 nativeKeysManager { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1495,7 +1519,7 @@ impl KeysManager { #[no_mangle] pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs: u64, mut starting_time_nanos: u32) -> KeysManager { let mut ret = lightning::chain::keysinterface::KeysManager::new(unsafe { &*seed}, starting_time_secs, starting_time_nanos); - KeysManager { inner: Box::into_raw(Box::new(ret)), is_owned: true } + KeysManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Derive an old Sign containing per-channel secrets based on a key derivation parameters. @@ -1506,8 +1530,8 @@ pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs: #[must_use] #[no_mangle] pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::lightning::chain::keysinterface::InMemorySigner { - let mut ret = unsafe { &*this_arg.inner }.derive_channel_keys(channel_value_satoshis, unsafe { &*params}); - crate::lightning::chain::keysinterface::InMemorySigner { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.derive_channel_keys(channel_value_satoshis, unsafe { &*params}); + crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a Transaction which spends the given descriptors to the given outputs, plus an @@ -1526,14 +1550,14 @@ pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &KeysManager, mut ch pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &KeysManager, mut descriptors: crate::c_types::derived::CVec_SpendableOutputDescriptorZ, mut outputs: crate::c_types::derived::CVec_TxOutZ, mut change_destination_script: crate::c_types::derived::CVec_u8Z, mut feerate_sat_per_1000_weight: u32) -> crate::c_types::derived::CResult_TransactionNoneZ { let mut local_descriptors = Vec::new(); for mut item in descriptors.into_rust().drain(..) { local_descriptors.push( { item.into_native() }); }; let mut local_outputs = Vec::new(); for mut item in outputs.into_rust().drain(..) { local_outputs.push( { item.into_rust() }); }; - let mut ret = unsafe { &*this_arg.inner }.spend_spendable_outputs(&local_descriptors.iter().collect::>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.spend_spendable_outputs(&local_descriptors.iter().collect::>()[..], local_outputs, ::bitcoin::blockdata::script::Script::from(change_destination_script.into_rust()), feerate_sat_per_1000_weight, secp256k1::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Transaction::from_bitcoin(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } impl From for crate::lightning::chain::keysinterface::KeysInterface { fn from(obj: nativeKeysManager) -> Self { - let mut rust_obj = KeysManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = KeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = KeysManager_as_KeysInterface(&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(); @@ -1546,7 +1570,7 @@ impl From for crate::lightning::chain::keysinterface::KeysInt #[no_mangle] pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::KeysInterface { crate::lightning::chain::keysinterface::KeysInterface { - 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_node_secret: KeysManager_KeysInterface_get_node_secret, get_destination_script: KeysManager_KeysInterface_get_destination_script, @@ -1571,7 +1595,7 @@ extern "C" fn KeysManager_KeysInterface_get_destination_script(this_arg: *const #[must_use] extern "C" fn KeysManager_KeysInterface_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript { let mut ret = >::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); - crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } #[must_use] extern "C" fn KeysManager_KeysInterface_get_channel_signer(this_arg: *const c_void, mut _inbound: bool, mut channel_value_satoshis: u64) -> crate::lightning::chain::keysinterface::Sign { @@ -1586,7 +1610,7 @@ extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const #[must_use] extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ { let mut ret = >::read_chan_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, reader.to_slice()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).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 mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o.into() }).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 } #[must_use] diff --git a/lightning-c-bindings/src/lightning/chain/mod.rs b/lightning-c-bindings/src/lightning/chain/mod.rs index 7db4732..9c8b4f5 100644 --- a/lightning-c-bindings/src/lightning/chain/mod.rs +++ b/lightning-c-bindings/src/lightning/chain/mod.rs @@ -57,7 +57,7 @@ pub struct BestBlock { impl Drop for BestBlock { fn drop(&mut self) { if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -70,11 +70,17 @@ extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBestBlock); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl BestBlock { + pub(crate) fn get_native_ref(&self) -> &'static nativeBestBlock { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBestBlock { + 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 nativeBestBlock { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -83,7 +89,7 @@ impl Clone for BestBlock { fn clone(&self) -> Self { Self { inner: if <*mut nativeBestBlock>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -104,7 +110,7 @@ pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock { #[no_mangle] pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock { let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin()); - BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true } + BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns a `BestBlock` as identified by the given block hash and height. @@ -112,14 +118,14 @@ pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::N #[no_mangle] pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock { let mut ret = lightning::chain::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height); - BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true } + BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns the best block hash. #[must_use] #[no_mangle] pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.block_hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_hash(); crate::c_types::ThirtyTwoBytes { data: ret.into_inner() } } @@ -127,7 +133,7 @@ pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types:: #[must_use] #[no_mangle] pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 { - let mut ret = unsafe { &*this_arg.inner }.height(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.height(); ret } @@ -510,12 +516,12 @@ pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch { use lightning::chain::Watch as rustWatch; impl rustWatch for Watch { fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { - let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(monitor)), is_owned: true }); + let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(monitor), is_owned: true }); 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(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> { - let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(funding_txo)), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(update)), is_owned: true }); + let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(update), is_owned: true }); 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(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } @@ -605,7 +611,7 @@ impl rustFilter for Filter { (self.register_tx)(self.this_arg, txid.as_inner(), crate::c_types::u8slice::from_slice(&script_pubkey[..])) } fn register_output(&self, mut output: lightning::chain::WatchedOutput) -> Option<(usize, bitcoin::blockdata::transaction::Transaction)> { - let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: Box::into_raw(Box::new(output)), is_owned: true }); + let mut ret = (self.register_output)(self.this_arg, crate::lightning::chain::WatchedOutput { inner: ObjOps::heap_alloc(output), is_owned: true }); let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = ret.take().to_rust(); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1.into_bitcoin()); local_ret_0 }) } else { None }; local_ret } @@ -662,7 +668,7 @@ pub struct WatchedOutput { impl Drop for WatchedOutput { fn drop(&mut self) { if self.is_owned && !<*mut nativeWatchedOutput>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -675,11 +681,17 @@ extern "C" fn WatchedOutput_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeWatchedOutput); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl WatchedOutput { + pub(crate) fn get_native_ref(&self) -> &'static nativeWatchedOutput { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeWatchedOutput { + 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 nativeWatchedOutput { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -689,7 +701,7 @@ impl WatchedOutput { /// 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 WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crate::c_types::ThirtyTwoBytes { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.block_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().block_hash; let mut local_inner_val = if inner_val.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (inner_val.unwrap()).into_inner() } } }; local_inner_val } @@ -699,46 +711,46 @@ pub extern "C" fn WatchedOutput_get_block_hash(this_ptr: &WatchedOutput) -> crat #[no_mangle] pub extern "C" fn WatchedOutput_set_block_hash(this_ptr: &mut WatchedOutput, mut val: crate::c_types::ThirtyTwoBytes) { let mut local_val = if val.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap() }) }; - unsafe { &mut *this_ptr.inner }.block_hash = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.block_hash = local_val; } /// Outpoint identifying the transaction output. #[no_mangle] pub extern "C" fn WatchedOutput_get_outpoint(this_ptr: &WatchedOutput) -> crate::lightning::chain::transaction::OutPoint { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outpoint; - crate::lightning::chain::transaction::OutPoint { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().outpoint; + crate::lightning::chain::transaction::OutPoint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Outpoint identifying the transaction output. #[no_mangle] pub extern "C" fn WatchedOutput_set_outpoint(this_ptr: &mut WatchedOutput, mut val: crate::lightning::chain::transaction::OutPoint) { - unsafe { &mut *this_ptr.inner }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outpoint = *unsafe { Box::from_raw(val.take_inner()) }; } /// Spending condition of the transaction output. #[no_mangle] pub extern "C" fn WatchedOutput_get_script_pubkey(this_ptr: &WatchedOutput) -> crate::c_types::u8slice { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.script_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().script_pubkey; crate::c_types::u8slice::from_slice(&inner_val[..]) } /// Spending condition of the transaction output. #[no_mangle] pub extern "C" fn WatchedOutput_set_script_pubkey(this_ptr: &mut WatchedOutput, mut val: crate::c_types::derived::CVec_u8Z) { - unsafe { &mut *this_ptr.inner }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust()); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script_pubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust()); } /// Constructs a new WatchedOutput given each field #[must_use] #[no_mangle] pub extern "C" fn WatchedOutput_new(mut block_hash_arg: crate::c_types::ThirtyTwoBytes, mut outpoint_arg: crate::lightning::chain::transaction::OutPoint, mut script_pubkey_arg: crate::c_types::derived::CVec_u8Z) -> WatchedOutput { let mut local_block_hash_arg = if block_hash_arg.data == [0; 32] { None } else { Some( { ::bitcoin::hash_types::BlockHash::from_slice(&block_hash_arg.data[..]).unwrap() }) }; - WatchedOutput { inner: Box::into_raw(Box::new(nativeWatchedOutput { + WatchedOutput { inner: ObjOps::heap_alloc(nativeWatchedOutput { block_hash: local_block_hash_arg, outpoint: *unsafe { Box::from_raw(outpoint_arg.take_inner()) }, script_pubkey: ::bitcoin::blockdata::script::Script::from(script_pubkey_arg.into_rust()), - })), is_owned: true } + }), is_owned: true } } impl Clone for WatchedOutput { fn clone(&self) -> Self { Self { inner: if <*mut nativeWatchedOutput>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -760,6 +772,6 @@ pub extern "C" fn WatchedOutput_hash(o: &WatchedOutput) -> u64 { // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core #[allow(deprecated)] let mut hasher = core::hash::SipHasher::new(); - std::hash::Hash::hash(unsafe { &*o.inner }, &mut hasher); + std::hash::Hash::hash(o.get_native_ref(), &mut hasher); std::hash::Hasher::finish(&hasher) } diff --git a/lightning-c-bindings/src/lightning/chain/transaction.rs b/lightning-c-bindings/src/lightning/chain/transaction.rs index 45794a1..2006596 100644 --- a/lightning-c-bindings/src/lightning/chain/transaction.rs +++ b/lightning-c-bindings/src/lightning/chain/transaction.rs @@ -39,7 +39,7 @@ pub struct OutPoint { impl Drop for OutPoint { fn drop(&mut self) { if self.is_owned && !<*mut nativeOutPoint>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -52,11 +52,17 @@ extern "C" fn OutPoint_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeOutPoint); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl OutPoint { + pub(crate) fn get_native_ref(&self) -> &'static nativeOutPoint { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOutPoint { + 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 nativeOutPoint { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -64,39 +70,39 @@ impl OutPoint { /// The referenced transaction's txid. #[no_mangle] pub extern "C" fn OutPoint_get_txid(this_ptr: &OutPoint) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.txid; + let mut inner_val = &mut this_ptr.get_native_mut_ref().txid; inner_val.as_inner() } /// The referenced transaction's txid. #[no_mangle] pub extern "C" fn OutPoint_set_txid(this_ptr: &mut OutPoint, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); } /// The index of the referenced output in its transaction's vout. #[no_mangle] pub extern "C" fn OutPoint_get_index(this_ptr: &OutPoint) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.index; + let mut inner_val = &mut this_ptr.get_native_mut_ref().index; *inner_val } /// The index of the referenced output in its transaction's vout. #[no_mangle] pub extern "C" fn OutPoint_set_index(this_ptr: &mut OutPoint, mut val: u16) { - unsafe { &mut *this_ptr.inner }.index = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.index = val; } /// Constructs a new OutPoint given each field #[must_use] #[no_mangle] pub extern "C" fn OutPoint_new(mut txid_arg: crate::c_types::ThirtyTwoBytes, mut index_arg: u16) -> OutPoint { - OutPoint { inner: Box::into_raw(Box::new(nativeOutPoint { + OutPoint { inner: ObjOps::heap_alloc(nativeOutPoint { txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(), index: index_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for OutPoint { fn clone(&self) -> Self { Self { inner: if <*mut nativeOutPoint>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -118,7 +124,7 @@ pub extern "C" fn OutPoint_clone(orig: &OutPoint) -> OutPoint { pub extern "C" fn OutPoint_eq(a: &OutPoint, b: &OutPoint) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } /// Checks if two OutPoints contain equal inner contents. #[no_mangle] @@ -127,21 +133,21 @@ pub extern "C" fn OutPoint_hash(o: &OutPoint) -> u64 { // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core #[allow(deprecated)] let mut hasher = core::hash::SipHasher::new(); - std::hash::Hash::hash(unsafe { &*o.inner }, &mut hasher); + std::hash::Hash::hash(o.get_native_ref(), &mut hasher); std::hash::Hasher::finish(&hasher) } /// Convert an `OutPoint` to a lightning channel id. #[must_use] #[no_mangle] pub extern "C" fn OutPoint_to_channel_id(this_arg: &OutPoint) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.to_channel_id(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_channel_id(); crate::c_types::ThirtyTwoBytes { data: ret } } #[no_mangle] /// Serialize the OutPoint object into a byte array which can be read by OutPoint_read pub extern "C" fn OutPoint_write(obj: &OutPoint) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -151,6 +157,6 @@ pub(crate) extern "C" fn OutPoint_write_void(obj: *const c_void) -> crate::c_typ /// Read a OutPoint from a byte array, created by OutPoint_write pub extern "C" fn OutPoint_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OutPointDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/ln/chan_utils.rs b/lightning-c-bindings/src/lightning/ln/chan_utils.rs index 5cf8b63..0fa8612 100644 --- a/lightning-c-bindings/src/lightning/ln/chan_utils.rs +++ b/lightning-c-bindings/src/lightning/ln/chan_utils.rs @@ -113,7 +113,7 @@ pub struct TxCreationKeys { impl Drop for TxCreationKeys { fn drop(&mut self) { if self.is_owned && !<*mut nativeTxCreationKeys>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -126,11 +126,17 @@ extern "C" fn TxCreationKeys_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeTxCreationKeys); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl TxCreationKeys { + pub(crate) fn get_native_ref(&self) -> &'static nativeTxCreationKeys { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTxCreationKeys { + 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 nativeTxCreationKeys { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -138,20 +144,20 @@ impl TxCreationKeys { /// The broadcaster's per-commitment public key which was used to derive the other keys. #[no_mangle] pub extern "C" fn TxCreationKeys_get_per_commitment_point(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The broadcaster's per-commitment public key which was used to derive the other keys. #[no_mangle] pub extern "C" fn TxCreationKeys_set_per_commitment_point(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.per_commitment_point = val.into_rust(); } /// The revocation key which is used to allow the broadcaster of the commitment /// transaction to provide their counterparty the ability to punish them if they broadcast /// an old state. #[no_mangle] pub extern "C" fn TxCreationKeys_get_revocation_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_key; crate::c_types::PublicKey::from_rust(&inner_val) } /// The revocation key which is used to allow the broadcaster of the commitment @@ -159,58 +165,58 @@ pub extern "C" fn TxCreationKeys_get_revocation_key(this_ptr: &TxCreationKeys) - /// an old state. #[no_mangle] pub extern "C" fn TxCreationKeys_set_revocation_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.revocation_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_key = val.into_rust(); } /// Broadcaster's HTLC Key #[no_mangle] pub extern "C" fn TxCreationKeys_get_broadcaster_htlc_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.broadcaster_htlc_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().broadcaster_htlc_key; crate::c_types::PublicKey::from_rust(&inner_val) } /// Broadcaster's HTLC Key #[no_mangle] pub extern "C" fn TxCreationKeys_set_broadcaster_htlc_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.broadcaster_htlc_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.broadcaster_htlc_key = val.into_rust(); } /// Countersignatory's HTLC Key #[no_mangle] pub extern "C" fn TxCreationKeys_get_countersignatory_htlc_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.countersignatory_htlc_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().countersignatory_htlc_key; crate::c_types::PublicKey::from_rust(&inner_val) } /// Countersignatory's HTLC Key #[no_mangle] pub extern "C" fn TxCreationKeys_set_countersignatory_htlc_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.countersignatory_htlc_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.countersignatory_htlc_key = val.into_rust(); } /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay) #[no_mangle] pub extern "C" fn TxCreationKeys_get_broadcaster_delayed_payment_key(this_ptr: &TxCreationKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.broadcaster_delayed_payment_key; + let mut inner_val = &mut this_ptr.get_native_mut_ref().broadcaster_delayed_payment_key; crate::c_types::PublicKey::from_rust(&inner_val) } /// Broadcaster's Payment Key (which isn't allowed to be spent from for some delay) #[no_mangle] pub extern "C" fn TxCreationKeys_set_broadcaster_delayed_payment_key(this_ptr: &mut TxCreationKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.broadcaster_delayed_payment_key = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.broadcaster_delayed_payment_key = val.into_rust(); } /// Constructs a new TxCreationKeys given each field #[must_use] #[no_mangle] pub extern "C" fn TxCreationKeys_new(mut per_commitment_point_arg: crate::c_types::PublicKey, mut revocation_key_arg: crate::c_types::PublicKey, mut broadcaster_htlc_key_arg: crate::c_types::PublicKey, mut countersignatory_htlc_key_arg: crate::c_types::PublicKey, mut broadcaster_delayed_payment_key_arg: crate::c_types::PublicKey) -> TxCreationKeys { - TxCreationKeys { inner: Box::into_raw(Box::new(nativeTxCreationKeys { + TxCreationKeys { inner: ObjOps::heap_alloc(nativeTxCreationKeys { per_commitment_point: per_commitment_point_arg.into_rust(), revocation_key: revocation_key_arg.into_rust(), broadcaster_htlc_key: broadcaster_htlc_key_arg.into_rust(), countersignatory_htlc_key: countersignatory_htlc_key_arg.into_rust(), broadcaster_delayed_payment_key: broadcaster_delayed_payment_key_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for TxCreationKeys { fn clone(&self) -> Self { Self { inner: if <*mut nativeTxCreationKeys>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -228,7 +234,7 @@ pub extern "C" fn TxCreationKeys_clone(orig: &TxCreationKeys) -> TxCreationKeys #[no_mangle] /// Serialize the TxCreationKeys object into a byte array which can be read by TxCreationKeys_read pub extern "C" fn TxCreationKeys_write(obj: &TxCreationKeys) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -238,7 +244,7 @@ pub(crate) extern "C" fn TxCreationKeys_write_void(obj: *const c_void) -> crate: /// Read a TxCreationKeys from a byte array, created by TxCreationKeys_write pub extern "C" fn TxCreationKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_TxCreationKeysDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -264,7 +270,7 @@ pub struct ChannelPublicKeys { impl Drop for ChannelPublicKeys { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelPublicKeys>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -277,11 +283,17 @@ extern "C" fn ChannelPublicKeys_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelPublicKeys); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelPublicKeys { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelPublicKeys { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelPublicKeys { + 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 nativeChannelPublicKeys { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -290,14 +302,14 @@ impl ChannelPublicKeys { /// on-chain channel lock-in 2-of-2 multisig output. #[no_mangle] pub extern "C" fn ChannelPublicKeys_get_funding_pubkey(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_pubkey; crate::c_types::PublicKey::from_rust(&inner_val) } /// The public key which is used to sign all commitment transactions, as it appears in the /// on-chain channel lock-in 2-of-2 multisig output. #[no_mangle] pub extern "C" fn ChannelPublicKeys_set_funding_pubkey(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.funding_pubkey = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_pubkey = val.into_rust(); } /// The base point which is used (with derive_public_revocation_key) to derive per-commitment /// revocation keys. This is combined with the per-commitment-secret generated by the @@ -305,7 +317,7 @@ pub extern "C" fn ChannelPublicKeys_set_funding_pubkey(this_ptr: &mut ChannelPub /// states. #[no_mangle] pub extern "C" fn ChannelPublicKeys_get_revocation_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// The base point which is used (with derive_public_revocation_key) to derive per-commitment @@ -314,14 +326,14 @@ pub extern "C" fn ChannelPublicKeys_get_revocation_basepoint(this_ptr: &ChannelP /// states. #[no_mangle] pub extern "C" fn ChannelPublicKeys_set_revocation_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.revocation_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_basepoint = val.into_rust(); } /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately /// spendable primary channel balance on the broadcaster's commitment transaction. This key is /// static across every commitment transaction. #[no_mangle] pub extern "C" fn ChannelPublicKeys_get_payment_point(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The public key on which the non-broadcaster (ie the countersignatory) receives an immediately @@ -329,14 +341,14 @@ pub extern "C" fn ChannelPublicKeys_get_payment_point(this_ptr: &ChannelPublicKe /// static across every commitment transaction. #[no_mangle] pub extern "C" fn ChannelPublicKeys_set_payment_point(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.payment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_point = val.into_rust(); } /// The base point which is used (with derive_public_key) to derive a per-commitment payment /// public key which receives non-HTLC-encumbered funds which are only available for spending /// after some delay (or can be claimed via the revocation path). #[no_mangle] pub extern "C" fn ChannelPublicKeys_get_delayed_payment_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// The base point which is used (with derive_public_key) to derive a per-commitment payment @@ -344,38 +356,38 @@ pub extern "C" fn ChannelPublicKeys_get_delayed_payment_basepoint(this_ptr: &Cha /// after some delay (or can be claimed via the revocation path). #[no_mangle] pub extern "C" fn ChannelPublicKeys_set_delayed_payment_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_basepoint = val.into_rust(); } /// The base point which is used (with derive_public_key) to derive a per-commitment public key /// which is used to encumber HTLC-in-flight outputs. #[no_mangle] pub extern "C" fn ChannelPublicKeys_get_htlc_basepoint(this_ptr: &ChannelPublicKeys) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// The base point which is used (with derive_public_key) to derive a per-commitment public key /// which is used to encumber HTLC-in-flight outputs. #[no_mangle] pub extern "C" fn ChannelPublicKeys_set_htlc_basepoint(this_ptr: &mut ChannelPublicKeys, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.htlc_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_basepoint = val.into_rust(); } /// Constructs a new ChannelPublicKeys given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelPublicKeys_new(mut funding_pubkey_arg: crate::c_types::PublicKey, mut revocation_basepoint_arg: crate::c_types::PublicKey, mut payment_point_arg: crate::c_types::PublicKey, mut delayed_payment_basepoint_arg: crate::c_types::PublicKey, mut htlc_basepoint_arg: crate::c_types::PublicKey) -> ChannelPublicKeys { - ChannelPublicKeys { inner: Box::into_raw(Box::new(nativeChannelPublicKeys { + ChannelPublicKeys { inner: ObjOps::heap_alloc(nativeChannelPublicKeys { funding_pubkey: funding_pubkey_arg.into_rust(), revocation_basepoint: revocation_basepoint_arg.into_rust(), payment_point: payment_point_arg.into_rust(), delayed_payment_basepoint: delayed_payment_basepoint_arg.into_rust(), htlc_basepoint: htlc_basepoint_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelPublicKeys { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelPublicKeys>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -393,7 +405,7 @@ pub extern "C" fn ChannelPublicKeys_clone(orig: &ChannelPublicKeys) -> ChannelPu #[no_mangle] /// Serialize the ChannelPublicKeys object into a byte array which can be read by ChannelPublicKeys_read pub extern "C" fn ChannelPublicKeys_write(obj: &ChannelPublicKeys) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -403,7 +415,7 @@ pub(crate) extern "C" fn ChannelPublicKeys_write_void(obj: *const c_void) -> cra /// Read a ChannelPublicKeys from a byte array, created by ChannelPublicKeys_write pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelPublicKeysDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Create per-state keys from channel base points and the per-commitment point. @@ -412,7 +424,7 @@ pub extern "C" fn ChannelPublicKeys_read(ser: crate::c_types::u8slice) -> crate: #[no_mangle] pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_types::PublicKey, mut broadcaster_delayed_payment_base: crate::c_types::PublicKey, mut broadcaster_htlc_base: crate::c_types::PublicKey, mut countersignatory_revocation_base: crate::c_types::PublicKey, mut countersignatory_htlc_base: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ { let mut ret = lightning::ln::chan_utils::TxCreationKeys::derive_new(secp256k1::SECP256K1, &per_commitment_point.into_rust(), &broadcaster_delayed_payment_base.into_rust(), &broadcaster_htlc_base.into_rust(), &countersignatory_revocation_base.into_rust(), &countersignatory_htlc_base.into_rust()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } @@ -421,8 +433,8 @@ pub extern "C" fn TxCreationKeys_derive_new(mut per_commitment_point: crate::c_t #[must_use] #[no_mangle] pub extern "C" fn TxCreationKeys_from_channel_static_keys(mut per_commitment_point: crate::c_types::PublicKey, broadcaster_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TxCreationKeysErrorZ { - let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; + let mut ret = lightning::ln::chan_utils::TxCreationKeys::from_channel_static_keys(&per_commitment_point.into_rust(), broadcaster_keys.get_native_ref(), countersignatory_keys.get_native_ref(), secp256k1::SECP256K1); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TxCreationKeys { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } @@ -462,7 +474,7 @@ pub struct HTLCOutputInCommitment { impl Drop for HTLCOutputInCommitment { fn drop(&mut self) { if self.is_owned && !<*mut nativeHTLCOutputInCommitment>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -475,11 +487,17 @@ extern "C" fn HTLCOutputInCommitment_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCOutputInCommitment); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl HTLCOutputInCommitment { + pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCOutputInCommitment { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCOutputInCommitment { + 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 nativeHTLCOutputInCommitment { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -490,7 +508,7 @@ impl HTLCOutputInCommitment { /// the counterparty or our own. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_get_offered(this_ptr: &HTLCOutputInCommitment) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.offered; + let mut inner_val = &mut this_ptr.get_native_mut_ref().offered; *inner_val } /// Whether the HTLC was \"offered\" (ie outbound in relation to this commitment transaction). @@ -499,49 +517,49 @@ pub extern "C" fn HTLCOutputInCommitment_get_offered(this_ptr: &HTLCOutputInComm /// the counterparty or our own. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_offered(this_ptr: &mut HTLCOutputInCommitment, mut val: bool) { - unsafe { &mut *this_ptr.inner }.offered = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.offered = val; } /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is /// this divided by 1000. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_get_amount_msat(this_ptr: &HTLCOutputInCommitment) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.amount_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat; *inner_val } /// The value, in msat, of the HTLC. The value as it appears in the commitment transaction is /// this divided by 1000. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_amount_msat(this_ptr: &mut HTLCOutputInCommitment, mut val: u64) { - unsafe { &mut *this_ptr.inner }.amount_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val; } /// The CLTV lock-time at which this HTLC expires. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_get_cltv_expiry(this_ptr: &HTLCOutputInCommitment) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry; *inner_val } /// The CLTV lock-time at which this HTLC expires. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_cltv_expiry(this_ptr: &mut HTLCOutputInCommitment, mut val: u32) { - unsafe { &mut *this_ptr.inner }.cltv_expiry = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry = val; } /// The hash of the preimage which unlocks this HTLC. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_get_payment_hash(this_ptr: &HTLCOutputInCommitment) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_hash; &inner_val.0 } /// The hash of the preimage which unlocks this HTLC. #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_payment_hash(this_ptr: &mut HTLCOutputInCommitment, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::PaymentHash(val.data); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_hash = ::lightning::ln::PaymentHash(val.data); } /// The position within the commitment transactions' outputs. This may be None if the value is /// below the dust limit (in which case no output appears in the commitment transaction and the /// value is spent to additional transaction fees). #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_get_transaction_output_index(this_ptr: &HTLCOutputInCommitment) -> crate::c_types::derived::COption_u32Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.transaction_output_index; + let mut inner_val = &mut this_ptr.get_native_mut_ref().transaction_output_index; 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 } @@ -551,26 +569,26 @@ pub extern "C" fn HTLCOutputInCommitment_get_transaction_output_index(this_ptr: #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_set_transaction_output_index(this_ptr: &mut HTLCOutputInCommitment, 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 }.transaction_output_index = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.transaction_output_index = local_val; } /// Constructs a new HTLCOutputInCommitment given each field #[must_use] #[no_mangle] pub extern "C" fn HTLCOutputInCommitment_new(mut offered_arg: bool, mut amount_msat_arg: u64, mut cltv_expiry_arg: u32, mut payment_hash_arg: crate::c_types::ThirtyTwoBytes, mut transaction_output_index_arg: crate::c_types::derived::COption_u32Z) -> HTLCOutputInCommitment { let mut local_transaction_output_index_arg = if transaction_output_index_arg.is_some() { Some( { transaction_output_index_arg.take() }) } else { None }; - HTLCOutputInCommitment { inner: Box::into_raw(Box::new(nativeHTLCOutputInCommitment { + HTLCOutputInCommitment { inner: ObjOps::heap_alloc(nativeHTLCOutputInCommitment { offered: offered_arg, amount_msat: amount_msat_arg, cltv_expiry: cltv_expiry_arg, payment_hash: ::lightning::ln::PaymentHash(payment_hash_arg.data), transaction_output_index: local_transaction_output_index_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for HTLCOutputInCommitment { fn clone(&self) -> Self { Self { inner: if <*mut nativeHTLCOutputInCommitment>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -588,7 +606,7 @@ pub extern "C" fn HTLCOutputInCommitment_clone(orig: &HTLCOutputInCommitment) -> #[no_mangle] /// Serialize the HTLCOutputInCommitment object into a byte array which can be read by HTLCOutputInCommitment_read pub extern "C" fn HTLCOutputInCommitment_write(obj: &HTLCOutputInCommitment) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -598,14 +616,14 @@ pub(crate) extern "C" fn HTLCOutputInCommitment_write_void(obj: *const c_void) - /// Read a HTLCOutputInCommitment from a byte array, created by HTLCOutputInCommitment_write pub extern "C" fn HTLCOutputInCommitment_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCOutputInCommitmentDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Gets the witness redeemscript for an HTLC output in a commitment transaction. Note that htlc /// does not need to have its previous_output_index filled. #[no_mangle] pub extern "C" fn get_htlc_redeemscript(htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment, keys: &crate::lightning::ln::chan_utils::TxCreationKeys) -> crate::c_types::derived::CVec_u8Z { - let mut ret = lightning::ln::chan_utils::get_htlc_redeemscript(unsafe { &*htlc.inner }, unsafe { &*keys.inner }); + let mut ret = lightning::ln::chan_utils::get_htlc_redeemscript(htlc.get_native_ref(), keys.get_native_ref()); ret.into_bytes().into() } @@ -626,7 +644,7 @@ pub extern "C" fn make_funding_redeemscript(mut broadcaster: crate::c_types::Pub /// commitment transaction). #[no_mangle] pub extern "C" fn build_htlc_transaction(commitment_txid: *const [u8; 32], mut feerate_per_kw: u32, mut contest_delay: u16, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment, mut broadcaster_delayed_payment_key: crate::c_types::PublicKey, mut revocation_key: crate::c_types::PublicKey) -> crate::c_types::Transaction { - let mut ret = lightning::ln::chan_utils::build_htlc_transaction(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*commitment_txid }[..]).unwrap(), feerate_per_kw, contest_delay, unsafe { &*htlc.inner }, &broadcaster_delayed_payment_key.into_rust(), &revocation_key.into_rust()); + let mut ret = lightning::ln::chan_utils::build_htlc_transaction(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*commitment_txid }[..]).unwrap(), feerate_per_kw, contest_delay, htlc.get_native_ref(), &broadcaster_delayed_payment_key.into_rust(), &revocation_key.into_rust()); crate::c_types::Transaction::from_bitcoin(&ret) } @@ -657,7 +675,7 @@ pub struct ChannelTransactionParameters { impl Drop for ChannelTransactionParameters { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelTransactionParameters>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -670,11 +688,17 @@ extern "C" fn ChannelTransactionParameters_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelTransactionParameters); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelTransactionParameters { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelTransactionParameters { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelTransactionParameters { + 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 nativeChannelTransactionParameters { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -682,37 +706,37 @@ impl ChannelTransactionParameters { /// Holder public keys #[no_mangle] pub extern "C" fn ChannelTransactionParameters_get_holder_pubkeys(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_pubkeys; - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().holder_pubkeys; + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Holder public keys #[no_mangle] pub extern "C" fn ChannelTransactionParameters_set_holder_pubkeys(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::ChannelPublicKeys) { - unsafe { &mut *this_ptr.inner }.holder_pubkeys = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.holder_pubkeys = *unsafe { Box::from_raw(val.take_inner()) }; } /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions #[no_mangle] pub extern "C" fn ChannelTransactionParameters_get_holder_selected_contest_delay(this_ptr: &ChannelTransactionParameters) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().holder_selected_contest_delay; *inner_val } /// The contest delay selected by the holder, which applies to counterparty-broadcast transactions #[no_mangle] pub extern "C" fn ChannelTransactionParameters_set_holder_selected_contest_delay(this_ptr: &mut ChannelTransactionParameters, mut val: u16) { - unsafe { &mut *this_ptr.inner }.holder_selected_contest_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.holder_selected_contest_delay = val; } /// Whether the holder is the initiator of this channel. /// This is an input to the commitment number obscure factor computation. #[no_mangle] pub extern "C" fn ChannelTransactionParameters_get_is_outbound_from_holder(this_ptr: &ChannelTransactionParameters) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_outbound_from_holder; + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_outbound_from_holder; *inner_val } /// Whether the holder is the initiator of this channel. /// This is an input to the commitment number obscure factor computation. #[no_mangle] pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_ptr: &mut ChannelTransactionParameters, mut val: bool) { - unsafe { &mut *this_ptr.inner }.is_outbound_from_holder = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_outbound_from_holder = val; } /// The late-bound counterparty channel transaction parameters. /// These parameters are populated at the point in the protocol where the counterparty provides them. @@ -720,8 +744,8 @@ pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_ /// 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 ChannelTransactionParameters_get_counterparty_parameters(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_parameters; - let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { 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().counterparty_parameters; + let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// The late-bound counterparty channel transaction parameters. @@ -731,15 +755,15 @@ pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_ #[no_mangle] pub extern "C" fn ChannelTransactionParameters_set_counterparty_parameters(this_ptr: &mut ChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.counterparty_parameters = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_parameters = local_val; } /// The late-bound funding outpoint /// /// 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 ChannelTransactionParameters_get_funding_outpoint(this_ptr: &ChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_outpoint; - 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_outpoint; + let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// The late-bound funding outpoint @@ -748,7 +772,7 @@ pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &C #[no_mangle] pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &mut ChannelTransactionParameters, 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_outpoint = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_outpoint = local_val; } /// Constructs a new ChannelTransactionParameters given each field #[must_use] @@ -756,19 +780,19 @@ pub extern "C" fn ChannelTransactionParameters_set_funding_outpoint(this_ptr: &m pub extern "C" fn ChannelTransactionParameters_new(mut holder_pubkeys_arg: crate::lightning::ln::chan_utils::ChannelPublicKeys, mut holder_selected_contest_delay_arg: u16, mut is_outbound_from_holder_arg: bool, mut counterparty_parameters_arg: crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters, mut funding_outpoint_arg: crate::lightning::chain::transaction::OutPoint) -> ChannelTransactionParameters { let mut local_counterparty_parameters_arg = if counterparty_parameters_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(counterparty_parameters_arg.take_inner()) } }) }; let mut local_funding_outpoint_arg = if funding_outpoint_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(funding_outpoint_arg.take_inner()) } }) }; - ChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeChannelTransactionParameters { + ChannelTransactionParameters { inner: ObjOps::heap_alloc(nativeChannelTransactionParameters { holder_pubkeys: *unsafe { Box::from_raw(holder_pubkeys_arg.take_inner()) }, holder_selected_contest_delay: holder_selected_contest_delay_arg, is_outbound_from_holder: is_outbound_from_holder_arg, counterparty_parameters: local_counterparty_parameters_arg, funding_outpoint: local_funding_outpoint_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelTransactionParameters { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -806,7 +830,7 @@ pub struct CounterpartyChannelTransactionParameters { impl Drop for CounterpartyChannelTransactionParameters { fn drop(&mut self) { if self.is_owned && !<*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -819,11 +843,17 @@ extern "C" fn CounterpartyChannelTransactionParameters_free_void(this_ptr: *mut unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCounterpartyChannelTransactionParameters); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl CounterpartyChannelTransactionParameters { + pub(crate) fn get_native_ref(&self) -> &'static nativeCounterpartyChannelTransactionParameters { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCounterpartyChannelTransactionParameters { + 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 nativeCounterpartyChannelTransactionParameters { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -831,39 +861,39 @@ impl CounterpartyChannelTransactionParameters { /// Counter-party public keys #[no_mangle] pub extern "C" fn CounterpartyChannelTransactionParameters_get_pubkeys(this_ptr: &CounterpartyChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.pubkeys; - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().pubkeys; + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Counter-party public keys #[no_mangle] pub extern "C" fn CounterpartyChannelTransactionParameters_set_pubkeys(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: crate::lightning::ln::chan_utils::ChannelPublicKeys) { - unsafe { &mut *this_ptr.inner }.pubkeys = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.pubkeys = *unsafe { Box::from_raw(val.take_inner()) }; } /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions #[no_mangle] pub extern "C" fn CounterpartyChannelTransactionParameters_get_selected_contest_delay(this_ptr: &CounterpartyChannelTransactionParameters) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.selected_contest_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().selected_contest_delay; *inner_val } /// The contest delay selected by the counterparty, which applies to holder-broadcast transactions #[no_mangle] pub extern "C" fn CounterpartyChannelTransactionParameters_set_selected_contest_delay(this_ptr: &mut CounterpartyChannelTransactionParameters, mut val: u16) { - unsafe { &mut *this_ptr.inner }.selected_contest_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.selected_contest_delay = val; } /// Constructs a new CounterpartyChannelTransactionParameters given each field #[must_use] #[no_mangle] pub extern "C" fn CounterpartyChannelTransactionParameters_new(mut pubkeys_arg: crate::lightning::ln::chan_utils::ChannelPublicKeys, mut selected_contest_delay_arg: u16) -> CounterpartyChannelTransactionParameters { - CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(nativeCounterpartyChannelTransactionParameters { + CounterpartyChannelTransactionParameters { inner: ObjOps::heap_alloc(nativeCounterpartyChannelTransactionParameters { pubkeys: *unsafe { Box::from_raw(pubkeys_arg.take_inner()) }, selected_contest_delay: selected_contest_delay_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for CounterpartyChannelTransactionParameters { fn clone(&self) -> Self { Self { inner: if <*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -882,7 +912,7 @@ pub extern "C" fn CounterpartyChannelTransactionParameters_clone(orig: &Counterp #[must_use] #[no_mangle] pub extern "C" fn ChannelTransactionParameters_is_populated(this_arg: &ChannelTransactionParameters) -> bool { - let mut ret = unsafe { &*this_arg.inner }.is_populated(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_populated(); ret } @@ -893,8 +923,8 @@ pub extern "C" fn ChannelTransactionParameters_is_populated(this_arg: &ChannelTr #[must_use] #[no_mangle] pub extern "C" fn ChannelTransactionParameters_as_holder_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { - let mut ret = unsafe { &*this_arg.inner }.as_holder_broadcastable(); - crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_holder_broadcastable(); + crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Convert the holder/counterparty parameters to broadcaster/countersignatory-organized parameters, @@ -904,14 +934,14 @@ pub extern "C" fn ChannelTransactionParameters_as_holder_broadcastable(this_arg: #[must_use] #[no_mangle] pub extern "C" fn ChannelTransactionParameters_as_counterparty_broadcastable(this_arg: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { - let mut ret = unsafe { &*this_arg.inner }.as_counterparty_broadcastable(); - crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_counterparty_broadcastable(); + crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters { inner: ObjOps::heap_alloc(ret), is_owned: true } } #[no_mangle] /// Serialize the CounterpartyChannelTransactionParameters object into a byte array which can be read by CounterpartyChannelTransactionParameters_read pub extern "C" fn CounterpartyChannelTransactionParameters_write(obj: &CounterpartyChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -921,13 +951,13 @@ pub(crate) extern "C" fn CounterpartyChannelTransactionParameters_write_void(obj /// Read a CounterpartyChannelTransactionParameters from a byte array, created by CounterpartyChannelTransactionParameters_write pub extern "C" fn CounterpartyChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyChannelTransactionParametersDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ChannelTransactionParameters object into a byte array which can be read by ChannelTransactionParameters_read pub extern "C" fn ChannelTransactionParameters_write(obj: &ChannelTransactionParameters) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -937,7 +967,7 @@ pub(crate) extern "C" fn ChannelTransactionParameters_write_void(obj: *const c_v /// Read a ChannelTransactionParameters from a byte array, created by ChannelTransactionParameters_write pub extern "C" fn ChannelTransactionParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTransactionParametersDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -967,7 +997,7 @@ pub struct DirectedChannelTransactionParameters { impl Drop for DirectedChannelTransactionParameters { fn drop(&mut self) { if self.is_owned && !<*mut nativeDirectedChannelTransactionParameters>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -980,11 +1010,17 @@ extern "C" fn DirectedChannelTransactionParameters_free_void(this_ptr: *mut c_vo unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDirectedChannelTransactionParameters); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl DirectedChannelTransactionParameters { + pub(crate) fn get_native_ref(&self) -> &'static nativeDirectedChannelTransactionParameters { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDirectedChannelTransactionParameters { + 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 nativeDirectedChannelTransactionParameters { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -993,16 +1029,16 @@ impl DirectedChannelTransactionParameters { #[must_use] #[no_mangle] pub extern "C" fn DirectedChannelTransactionParameters_broadcaster_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut ret = unsafe { &*this_arg.inner }.broadcaster_pubkeys(); - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.broadcaster_pubkeys(); + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Get the channel pubkeys for the countersignatory #[must_use] #[no_mangle] pub extern "C" fn DirectedChannelTransactionParameters_countersignatory_pubkeys(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut ret = unsafe { &*this_arg.inner }.countersignatory_pubkeys(); - crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.countersignatory_pubkeys(); + crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Get the contest delay applicable to the transactions. @@ -1010,7 +1046,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_countersignatory_pubkeys( #[must_use] #[no_mangle] pub extern "C" fn DirectedChannelTransactionParameters_contest_delay(this_arg: &DirectedChannelTransactionParameters) -> u16 { - let mut ret = unsafe { &*this_arg.inner }.contest_delay(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.contest_delay(); ret } @@ -1021,7 +1057,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_contest_delay(this_arg: & #[must_use] #[no_mangle] pub extern "C" fn DirectedChannelTransactionParameters_is_outbound(this_arg: &DirectedChannelTransactionParameters) -> bool { - let mut ret = unsafe { &*this_arg.inner }.is_outbound(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_outbound(); ret } @@ -1029,7 +1065,7 @@ pub extern "C" fn DirectedChannelTransactionParameters_is_outbound(this_arg: &Di #[must_use] #[no_mangle] pub extern "C" fn DirectedChannelTransactionParameters_funding_outpoint(this_arg: &DirectedChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint { - let mut ret = unsafe { &*this_arg.inner }.funding_outpoint(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_outpoint(); crate::c_types::bitcoin_to_C_outpoint(ret) } @@ -1058,7 +1094,7 @@ pub struct HolderCommitmentTransaction { impl Drop for HolderCommitmentTransaction { fn drop(&mut self) { if self.is_owned && !<*mut nativeHolderCommitmentTransaction>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1071,11 +1107,17 @@ extern "C" fn HolderCommitmentTransaction_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHolderCommitmentTransaction); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl HolderCommitmentTransaction { + pub(crate) fn get_native_ref(&self) -> &'static nativeHolderCommitmentTransaction { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHolderCommitmentTransaction { + 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 nativeHolderCommitmentTransaction { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1083,25 +1125,25 @@ impl HolderCommitmentTransaction { /// Our counterparty's signature for the transaction #[no_mangle] pub extern "C" fn HolderCommitmentTransaction_get_counterparty_sig(this_ptr: &HolderCommitmentTransaction) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_sig; + let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty_sig; crate::c_types::Signature::from_rust(&inner_val) } /// Our counterparty's signature for the transaction #[no_mangle] pub extern "C" fn HolderCommitmentTransaction_set_counterparty_sig(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.counterparty_sig = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_sig = val.into_rust(); } /// All non-dust counterparty HTLC signatures, in the order they appear in the transaction #[no_mangle] pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_ptr: &mut HolderCommitmentTransaction, mut val: crate::c_types::derived::CVec_SignatureZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); }; - unsafe { &mut *this_ptr.inner }.counterparty_htlc_sigs = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.counterparty_htlc_sigs = local_val; } impl Clone for HolderCommitmentTransaction { fn clone(&self) -> Self { Self { inner: if <*mut nativeHolderCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1119,7 +1161,7 @@ pub extern "C" fn HolderCommitmentTransaction_clone(orig: &HolderCommitmentTrans #[no_mangle] /// Serialize the HolderCommitmentTransaction object into a byte array which can be read by HolderCommitmentTransaction_read pub extern "C" fn HolderCommitmentTransaction_write(obj: &HolderCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1129,7 +1171,7 @@ pub(crate) extern "C" fn HolderCommitmentTransaction_write_void(obj: *const c_vo /// Read a HolderCommitmentTransaction from a byte array, created by HolderCommitmentTransaction_write pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HolderCommitmentTransactionDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Create a new holder transaction with the given counterparty signatures. @@ -1139,7 +1181,7 @@ pub extern "C" fn HolderCommitmentTransaction_read(ser: crate::c_types::u8slice) pub extern "C" fn HolderCommitmentTransaction_new(mut commitment_tx: crate::lightning::ln::chan_utils::CommitmentTransaction, mut counterparty_sig: crate::c_types::Signature, mut counterparty_htlc_sigs: crate::c_types::derived::CVec_SignatureZ, mut holder_funding_key: crate::c_types::PublicKey, mut counterparty_funding_key: crate::c_types::PublicKey) -> HolderCommitmentTransaction { let mut local_counterparty_htlc_sigs = Vec::new(); for mut item in counterparty_htlc_sigs.into_rust().drain(..) { local_counterparty_htlc_sigs.push( { item.into_rust() }); }; let mut ret = lightning::ln::chan_utils::HolderCommitmentTransaction::new(*unsafe { Box::from_raw(commitment_tx.take_inner()) }, counterparty_sig.into_rust(), local_counterparty_htlc_sigs, &holder_funding_key.into_rust(), &counterparty_funding_key.into_rust()); - HolderCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true } + HolderCommitmentTransaction { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -1165,7 +1207,7 @@ pub struct BuiltCommitmentTransaction { impl Drop for BuiltCommitmentTransaction { fn drop(&mut self) { if self.is_owned && !<*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1178,11 +1220,17 @@ extern "C" fn BuiltCommitmentTransaction_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBuiltCommitmentTransaction); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl BuiltCommitmentTransaction { + pub(crate) fn get_native_ref(&self) -> &'static nativeBuiltCommitmentTransaction { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBuiltCommitmentTransaction { + 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 nativeBuiltCommitmentTransaction { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1190,13 +1238,13 @@ impl BuiltCommitmentTransaction { /// The commitment transaction #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_get_transaction(this_ptr: &BuiltCommitmentTransaction) -> crate::c_types::Transaction { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.transaction; + let mut inner_val = &mut this_ptr.get_native_mut_ref().transaction; crate::c_types::Transaction::from_bitcoin(inner_val) } /// The commitment transaction #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_set_transaction(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::Transaction) { - unsafe { &mut *this_ptr.inner }.transaction = val.into_bitcoin(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.transaction = val.into_bitcoin(); } /// The txid for the commitment transaction. /// @@ -1204,7 +1252,7 @@ pub extern "C" fn BuiltCommitmentTransaction_set_transaction(this_ptr: &mut Buil /// multiple times. #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_get_txid(this_ptr: &BuiltCommitmentTransaction) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.txid; + let mut inner_val = &mut this_ptr.get_native_mut_ref().txid; inner_val.as_inner() } /// The txid for the commitment transaction. @@ -1213,22 +1261,22 @@ pub extern "C" fn BuiltCommitmentTransaction_get_txid(this_ptr: &BuiltCommitment /// multiple times. #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_set_txid(this_ptr: &mut BuiltCommitmentTransaction, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); } /// Constructs a new BuiltCommitmentTransaction given each field #[must_use] #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_new(mut transaction_arg: crate::c_types::Transaction, mut txid_arg: crate::c_types::ThirtyTwoBytes) -> BuiltCommitmentTransaction { - BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(nativeBuiltCommitmentTransaction { + BuiltCommitmentTransaction { inner: ObjOps::heap_alloc(nativeBuiltCommitmentTransaction { transaction: transaction_arg.into_bitcoin(), txid: ::bitcoin::hash_types::Txid::from_slice(&txid_arg.data[..]).unwrap(), - })), is_owned: true } + }), is_owned: true } } impl Clone for BuiltCommitmentTransaction { fn clone(&self) -> Self { Self { inner: if <*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1246,7 +1294,7 @@ pub extern "C" fn BuiltCommitmentTransaction_clone(orig: &BuiltCommitmentTransac #[no_mangle] /// Serialize the BuiltCommitmentTransaction object into a byte array which can be read by BuiltCommitmentTransaction_read pub extern "C" fn BuiltCommitmentTransaction_write(obj: &BuiltCommitmentTransaction) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1256,7 +1304,7 @@ pub(crate) extern "C" fn BuiltCommitmentTransaction_write_void(obj: *const c_voi /// Read a BuiltCommitmentTransaction from a byte array, created by BuiltCommitmentTransaction_write pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BuiltCommitmentTransactionDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Get the SIGHASH_ALL sighash value of the transaction. @@ -1265,7 +1313,7 @@ pub extern "C" fn BuiltCommitmentTransaction_read(ser: crate::c_types::u8slice) #[must_use] #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCommitmentTransaction, mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.get_sighash_all(&::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_sighash_all(&::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis); crate::c_types::ThirtyTwoBytes { data: ret.as_ref().clone() } } @@ -1274,7 +1322,7 @@ pub extern "C" fn BuiltCommitmentTransaction_get_sighash_all(this_arg: &BuiltCom #[must_use] #[no_mangle] pub extern "C" fn BuiltCommitmentTransaction_sign(this_arg: &BuiltCommitmentTransaction, funding_key: *const [u8; 32], mut funding_redeemscript: crate::c_types::u8slice, mut channel_value_satoshis: u64) -> crate::c_types::Signature { - let mut ret = unsafe { &*this_arg.inner }.sign(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, secp256k1::SECP256K1); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *funding_key}[..]).unwrap(), &::bitcoin::blockdata::script::Script::from(Vec::from(funding_redeemscript.to_slice())), channel_value_satoshis, secp256k1::SECP256K1); crate::c_types::Signature::from_rust(&ret) } @@ -1306,7 +1354,7 @@ pub struct CommitmentTransaction { impl Drop for CommitmentTransaction { fn drop(&mut self) { if self.is_owned && !<*mut nativeCommitmentTransaction>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1319,11 +1367,17 @@ extern "C" fn CommitmentTransaction_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCommitmentTransaction); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl CommitmentTransaction { + pub(crate) fn get_native_ref(&self) -> &'static nativeCommitmentTransaction { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCommitmentTransaction { + 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 nativeCommitmentTransaction { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1332,7 +1386,7 @@ impl Clone for CommitmentTransaction { fn clone(&self) -> Self { Self { inner: if <*mut nativeCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1350,7 +1404,7 @@ pub extern "C" fn CommitmentTransaction_clone(orig: &CommitmentTransaction) -> C #[no_mangle] /// Serialize the CommitmentTransaction object into a byte array which can be read by CommitmentTransaction_read pub extern "C" fn CommitmentTransaction_write(obj: &CommitmentTransaction) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1360,14 +1414,14 @@ pub(crate) extern "C" fn CommitmentTransaction_write_void(obj: *const c_void) -> /// Read a CommitmentTransaction from a byte array, created by CommitmentTransaction_write pub extern "C" fn CommitmentTransaction_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentTransactionDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// The backwards-counting commitment number #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_commitment_number(this_arg: &CommitmentTransaction) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.commitment_number(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.commitment_number(); ret } @@ -1375,7 +1429,7 @@ pub extern "C" fn CommitmentTransaction_commitment_number(this_arg: &CommitmentT #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_to_broadcaster_value_sat(this_arg: &CommitmentTransaction) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.to_broadcaster_value_sat(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_broadcaster_value_sat(); ret } @@ -1383,7 +1437,7 @@ pub extern "C" fn CommitmentTransaction_to_broadcaster_value_sat(this_arg: &Comm #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_to_countersignatory_value_sat(this_arg: &CommitmentTransaction) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.to_countersignatory_value_sat(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.to_countersignatory_value_sat(); ret } @@ -1391,7 +1445,7 @@ pub extern "C" fn CommitmentTransaction_to_countersignatory_value_sat(this_arg: #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_feerate_per_kw(this_arg: &CommitmentTransaction) -> u32 { - let mut ret = unsafe { &*this_arg.inner }.feerate_per_kw(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.feerate_per_kw(); ret } @@ -1404,8 +1458,8 @@ pub extern "C" fn CommitmentTransaction_feerate_per_kw(this_arg: &CommitmentTran #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction) -> crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { - let mut ret = unsafe { &*this_arg.inner }.trust(); - crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.trust(); + crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Verify our pre-built transaction and derived transaction creation public keys. @@ -1417,8 +1471,8 @@ pub extern "C" fn CommitmentTransaction_trust(this_arg: &CommitmentTransaction) #[must_use] #[no_mangle] pub extern "C" fn CommitmentTransaction_verify(this_arg: &CommitmentTransaction, channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters, broadcaster_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys, countersignatory_keys: &crate::lightning::ln::chan_utils::ChannelPublicKeys) -> crate::c_types::derived::CResult_TrustedCommitmentTransactionNoneZ { - let mut ret = unsafe { &*this_arg.inner }.verify(unsafe { &*channel_parameters.inner }, unsafe { &*broadcaster_keys.inner }, unsafe { &*countersignatory_keys.inner }, secp256k1::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.verify(channel_parameters.get_native_ref(), broadcaster_keys.get_native_ref(), countersignatory_keys.get_native_ref(), secp256k1::SECP256K1); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::TrustedCommitmentTransaction { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -1450,7 +1504,7 @@ pub struct TrustedCommitmentTransaction { impl Drop for TrustedCommitmentTransaction { fn drop(&mut self) { if self.is_owned && !<*mut nativeTrustedCommitmentTransaction>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1463,11 +1517,17 @@ extern "C" fn TrustedCommitmentTransaction_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeTrustedCommitmentTransaction); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl TrustedCommitmentTransaction { + pub(crate) fn get_native_ref(&self) -> &'static nativeTrustedCommitmentTransaction { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeTrustedCommitmentTransaction { + 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 nativeTrustedCommitmentTransaction { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1476,7 +1536,7 @@ impl TrustedCommitmentTransaction { #[must_use] #[no_mangle] pub extern "C" fn TrustedCommitmentTransaction_txid(this_arg: &TrustedCommitmentTransaction) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.txid(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.txid(); crate::c_types::ThirtyTwoBytes { data: ret.into_inner() } } @@ -1484,16 +1544,16 @@ pub extern "C" fn TrustedCommitmentTransaction_txid(this_arg: &TrustedCommitment #[must_use] #[no_mangle] pub extern "C" fn TrustedCommitmentTransaction_built_transaction(this_arg: &TrustedCommitmentTransaction) -> crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { - let mut ret = unsafe { &*this_arg.inner }.built_transaction(); - crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.built_transaction(); + crate::lightning::ln::chan_utils::BuiltCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// The pre-calculated transaction creation public keys. #[must_use] #[no_mangle] pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitmentTransaction) -> crate::lightning::ln::chan_utils::TxCreationKeys { - let mut ret = unsafe { &*this_arg.inner }.keys(); - crate::lightning::ln::chan_utils::TxCreationKeys { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.keys(); + crate::lightning::ln::chan_utils::TxCreationKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Get a signature for each HTLC which was included in the commitment transaction (ie for @@ -1503,7 +1563,7 @@ pub extern "C" fn TrustedCommitmentTransaction_keys(this_arg: &TrustedCommitment #[must_use] #[no_mangle] pub extern "C" fn TrustedCommitmentTransaction_get_htlc_sigs(this_arg: &TrustedCommitmentTransaction, htlc_base_key: *const [u8; 32], channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ { - let mut ret = unsafe { &*this_arg.inner }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), unsafe { &*channel_parameters.inner }, secp256k1::SECP256K1); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_htlc_sigs(&::bitcoin::secp256k1::key::SecretKey::from_slice(&unsafe { *htlc_base_key}[..]).unwrap(), channel_parameters.get_native_ref(), secp256k1::SECP256K1); 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( { crate::c_types::Signature::from_rust(&item) }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/ln/channelmanager.rs b/lightning-c-bindings/src/lightning/ln/channelmanager.rs index 0f5d3cc..8982a2b 100644 --- a/lightning-c-bindings/src/lightning/ln/channelmanager.rs +++ b/lightning-c-bindings/src/lightning/ln/channelmanager.rs @@ -80,7 +80,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)) }; } } } @@ -93,11 +93,17 @@ extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) { unsafe { let _ = 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -129,7 +135,7 @@ 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) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -142,11 +148,17 @@ extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainParameters); } } #[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 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 = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -154,43 +166,43 @@ impl ChainParameters { /// 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 unsafe { &mut *this_ptr.inner }.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 *this_ptr.inner }.network = val.into_bitcoin(); + 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 unsafe { &mut *this_ptr.inner }.best_block; - crate::lightning::chain::BestBlock { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + 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 _) 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 *this_ptr.inner }.best_block = *unsafe { Box::from_raw(val.take_inner()) }; + 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: Box::into_raw(Box::new(nativeChainParameters { + 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 } + }), is_owned: true } } impl Clone for ChainParameters { 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())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -253,7 +265,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)) }; } } } @@ -266,11 +278,17 @@ extern "C" fn ChannelCounterparty_free_void(this_ptr: *mut c_void) { unsafe { let _ = 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -278,28 +296,28 @@ impl ChannelCounterparty { /// 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 _) 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 +328,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 +340,13 @@ 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; } 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())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -366,7 +384,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)) }; } } } @@ -379,11 +397,17 @@ extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) { unsafe { let _ = 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -394,7 +418,7 @@ 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; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes, @@ -403,18 +427,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 = 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 _) 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 +449,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() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// The Channel's funding transaction output, if we've negotiated the funding transaction with @@ -439,13 +463,13 @@ 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 position of the funding transaction in the chain. None if the funding transaction has /// not yet been confirmed and the channel fully opened. #[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 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 } @@ -454,18 +478,18 @@ pub extern "C" fn ChannelDetails_get_short_channel_id(this_ptr: &ChannelDetails) #[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; } /// 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,7 +502,7 @@ 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 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 } @@ -494,18 +518,18 @@ 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_id passed in to create_channel, or 0 if the channel was inbound. #[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; + let mut inner_val = &mut this_ptr.get_native_mut_ref().user_id; *inner_val } /// The user_id passed in to create_channel, or 0 if the channel was inbound. #[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; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.user_id = 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 @@ -517,7 +541,7 @@ pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut /// 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 @@ -530,7 +554,7 @@ pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDe /// 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 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 @@ -543,7 +567,7 @@ 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 @@ -557,7 +581,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,7 +596,7 @@ 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 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 } @@ -590,7 +614,7 @@ 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 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,7 +625,7 @@ 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 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 } @@ -615,18 +639,18 @@ 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 @@ -637,7 +661,7 @@ pub extern "C" fn ChannelDetails_set_is_outbound(this_ptr: &mut ChannelDetails, /// [`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; + let mut inner_val = &mut this_ptr.get_native_mut_ref().is_funding_locked; *inner_val } /// True if the channel is confirmed, funding_locked messages have been exchanged, and the @@ -649,7 +673,7 @@ pub extern "C" fn ChannelDetails_get_is_funding_locked(this_ptr: &ChannelDetails /// [`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; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.is_funding_locked = val; } /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b) /// the peer is connected, and (c) the channel is not currently negotiating a shutdown. @@ -657,7 +681,7 @@ pub extern "C" fn ChannelDetails_set_is_funding_locked(this_ptr: &mut ChannelDet /// This is a strict superset of `is_funding_locked`. #[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) @@ -666,18 +690,18 @@ pub extern "C" fn ChannelDetails_get_is_usable(this_ptr: &ChannelDetails) -> boo /// This is a strict superset of `is_funding_locked`. #[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; } /// Constructs a new ChannelDetails given each field #[must_use] @@ -688,7 +712,7 @@ pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyT 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_confirmations_required_arg = if confirmations_required_arg.is_some() { Some( { confirmations_required_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 { + ChannelDetails { inner: ObjOps::heap_alloc(nativeChannelDetails { channel_id: channel_id_arg.data, counterparty: *unsafe { Box::from_raw(counterparty_arg.take_inner()) }, funding_txo: local_funding_txo_arg, @@ -704,13 +728,13 @@ pub extern "C" fn ChannelDetails_new(mut channel_id_arg: crate::c_types::ThirtyT is_funding_locked: is_funding_locked_arg, is_usable: is_usable_arg, is_public: is_public_arg, - })), is_owned: true } + }), 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())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -929,15 +953,15 @@ pub extern "C" fn PaymentSendFailure_partial_failure(a: crate::c_types::derived: #[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 } + ChannelManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Gets the current configuration applied to all new channels, as #[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 } + 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 _) as *mut _) }, is_owned: false } } /// Creates a new outbound channel to the given remote node and with the given value. @@ -963,7 +987,7 @@ pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &Ch #[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 { 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 ret = unsafe { &*ObjOps::untweak_ptr(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() }; local_ret } @@ -973,8 +997,8 @@ pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut t #[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 } }); }; + 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() } @@ -987,8 +1011,8 @@ pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> cra #[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 } }); }; + 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() } @@ -1012,7 +1036,7 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) #[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}); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel(unsafe { &*channel_id}); 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 } @@ -1039,7 +1063,7 @@ pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channe #[must_use] #[no_mangle] pub extern "C" fn ChannelManager_close_channel_with_target_feerate(this_arg: &ChannelManager, channel_id: *const [u8; 32], mut target_feerate_sats_per_1000_weight: u32) -> crate::c_types::derived::CResult_NoneAPIErrorZ { - let mut ret = unsafe { &*this_arg.inner }.close_channel_with_target_feerate(unsafe { &*channel_id}, target_feerate_sats_per_1000_weight); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel_with_target_feerate(unsafe { &*channel_id}, target_feerate_sats_per_1000_weight); 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 } @@ -1049,7 +1073,7 @@ pub extern "C" fn ChannelManager_close_channel_with_target_feerate(this_arg: &Ch #[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}); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_channel(unsafe { &*channel_id}); 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 } @@ -1058,7 +1082,7 @@ pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, /// 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() + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels() } /// Sends a payment along a given route. @@ -1106,7 +1130,7 @@ pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelMana #[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 ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment(route.get_native_ref(), ::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() }; local_ret } @@ -1131,7 +1155,7 @@ pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: #[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 ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment(route.get_native_ref(), 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() }; local_ret } @@ -1159,7 +1183,7 @@ pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &ChannelMana #[must_use] #[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 ret = unsafe { &*ObjOps::untweak_ptr(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 } @@ -1185,7 +1209,7 @@ pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &Channe #[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) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.broadcast_node_announcement(rgb.data, alias.data, local_addresses) } /// Processes HTLCs which are pending waiting on random forward delay. @@ -1194,7 +1218,7 @@ pub extern "C" fn ChannelManager_broadcast_node_announcement(this_arg: &ChannelM /// Will likely generate further events. #[no_mangle] pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.process_pending_htlc_forwards() + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_pending_htlc_forwards() } /// Performs actions which should happen on startup and roughly once per minute thereafter. @@ -1209,7 +1233,7 @@ pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &Channe /// estimate fetches. #[no_mangle] pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.timer_tick_occurred() + 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 @@ -1220,7 +1244,7 @@ pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) #[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 })); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash })); ret } @@ -1240,7 +1264,7 @@ pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, #[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)); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds(::lightning::ln::PaymentPreimage(payment_preimage.data)); ret } @@ -1248,7 +1272,7 @@ pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut paym #[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(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_our_node_id(); crate::c_types::PublicKey::from_rust(&ret) } @@ -1274,7 +1298,7 @@ pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> c /// completed, and once it is the latest the Channel will be re-enabled. #[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) + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_monitor_updated(funding_txo.get_native_ref(), highest_applied_update_id) } /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing @@ -1297,7 +1321,7 @@ pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManag #[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 { 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 ret = unsafe { &*ObjOps::untweak_ptr(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(); local_ret } @@ -1351,14 +1375,14 @@ pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &ChannelManage #[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 { 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 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, user_payment_id); 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 { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = 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(); @@ -1371,7 +1395,7 @@ impl From for crate::lightning::util::events::MessageSendE #[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 }, + 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, } @@ -1386,7 +1410,7 @@ extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg impl From for crate::lightning::util::events::EventsProvider { fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = 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(); @@ -1399,7 +1423,7 @@ impl From for crate::lightning::util::events::EventsProvid #[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 }, + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, process_pending_events: ChannelManager_EventsProvider_process_pending_events, } @@ -1411,7 +1435,7 @@ extern "C" fn ChannelManager_EventsProvider_process_pending_events(this_arg: *co 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 mut rust_obj = 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(); @@ -1424,7 +1448,7 @@ 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, block_connected: ChannelManager_Listen_block_connected, block_disconnected: ChannelManager_Listen_block_disconnected, @@ -1440,7 +1464,7 @@ 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 mut rust_obj = 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(); @@ -1453,7 +1477,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, @@ -1487,7 +1511,7 @@ extern "C" fn ChannelManager_Confirm_transaction_unconfirmed(this_arg: *const c_ #[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)); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.await_persistable_update_timeout(std::time::Duration::from_secs(max_wait)); ret } @@ -1496,7 +1520,7 @@ pub extern "C" fn ChannelManager_await_persistable_update_timeout(this_arg: &Cha /// up. #[no_mangle] pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelManager) { - unsafe { &*this_arg.inner }.await_persistable_update() + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.await_persistable_update() } /// Gets the latest best block which was connected either via the [`chain::Listen`] or @@ -1504,13 +1528,13 @@ pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelMana #[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 } + 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 } } 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 mut rust_obj = 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(); @@ -1523,7 +1547,7 @@ 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_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel, @@ -1546,7 +1570,7 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana 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 }, + 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, }, @@ -1554,70 +1578,70 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana } 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 }) + >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, 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 }) + >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, 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 }) + >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), their_features.get_native_ref(), 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 }) + >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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 }) + >::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_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_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 }) + >::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), init_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 }) + >::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), msg.get_native_ref()) } #[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 }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1670,7 +1694,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)) }; } } } @@ -1683,11 +1707,17 @@ extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) { unsafe { let _ = 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1697,7 +1727,7 @@ impl ChannelManagerReadArgs { /// 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; + let mut inner_val = &mut this_ptr.get_native_mut_ref().keys_manager; inner_val } /// The keys provider which will give us relevant keys. Some keys will be loaded during @@ -1705,14 +1735,14 @@ pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelMana /// 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; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.keys_manager = 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. @@ -1720,7 +1750,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. /// @@ -1729,7 +1759,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. @@ -1739,14 +1769,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 @@ -1754,33 +1784,33 @@ 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 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 _) 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 @@ -1788,9 +1818,9 @@ pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut Chann #[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 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(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 } + ChannelManagerReadArgs { inner: ObjOps::heap_alloc(ret), is_owned: true } } #[no_mangle] @@ -1798,6 +1828,6 @@ pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning: 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 { 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 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: 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 { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/ln/features.rs b/lightning-c-bindings/src/lightning/ln/features.rs index 8a61a85..ba3d779 100644 --- a/lightning-c-bindings/src/lightning/ln/features.rs +++ b/lightning-c-bindings/src/lightning/ln/features.rs @@ -41,7 +41,7 @@ use crate::c_types::*; pub extern "C" fn InitFeatures_eq(a: &InitFeatures, b: &InitFeatures) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } /// Checks if two NodeFeaturess contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -50,7 +50,7 @@ pub extern "C" fn InitFeatures_eq(a: &InitFeatures, b: &InitFeatures) -> bool { pub extern "C" fn NodeFeatures_eq(a: &NodeFeatures, b: &NodeFeatures) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } /// Checks if two ChannelFeaturess contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -59,7 +59,7 @@ pub extern "C" fn NodeFeatures_eq(a: &NodeFeatures, b: &NodeFeatures) -> bool { pub extern "C" fn ChannelFeatures_eq(a: &ChannelFeatures, b: &ChannelFeatures) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } /// Checks if two InvoiceFeaturess contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -68,13 +68,13 @@ pub extern "C" fn ChannelFeatures_eq(a: &ChannelFeatures, b: &ChannelFeatures) - pub extern "C" fn InvoiceFeatures_eq(a: &InvoiceFeatures, b: &InvoiceFeatures) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for InitFeatures { fn clone(&self) -> Self { Self { inner: if <*mut nativeInitFeatures>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -93,7 +93,7 @@ impl Clone for NodeFeatures { fn clone(&self) -> Self { Self { inner: if <*mut nativeNodeFeatures>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -112,7 +112,7 @@ impl Clone for ChannelFeatures { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelFeatures>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -131,7 +131,7 @@ impl Clone for InvoiceFeatures { fn clone(&self) -> Self { Self { inner: if <*mut nativeInvoiceFeatures>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -169,7 +169,7 @@ pub struct InitFeatures { impl Drop for InitFeatures { fn drop(&mut self) { if self.is_owned && !<*mut nativeInitFeatures>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -182,11 +182,17 @@ extern "C" fn InitFeatures_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInitFeatures); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InitFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeInitFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInitFeatures { + 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 nativeInitFeatures { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -214,7 +220,7 @@ pub struct NodeFeatures { impl Drop for NodeFeatures { fn drop(&mut self) { if self.is_owned && !<*mut nativeNodeFeatures>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -227,11 +233,17 @@ extern "C" fn NodeFeatures_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNodeFeatures); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NodeFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeNodeFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNodeFeatures { + 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 nativeNodeFeatures { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -259,7 +271,7 @@ pub struct ChannelFeatures { impl Drop for ChannelFeatures { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelFeatures>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -272,11 +284,17 @@ extern "C" fn ChannelFeatures_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelFeatures); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelFeatures { + 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 nativeChannelFeatures { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -304,7 +322,7 @@ pub struct InvoiceFeatures { impl Drop for InvoiceFeatures { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvoiceFeatures>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -317,11 +335,17 @@ extern "C" fn InvoiceFeatures_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoiceFeatures); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InvoiceFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvoiceFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoiceFeatures { + 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 nativeInvoiceFeatures { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -331,7 +355,7 @@ impl InvoiceFeatures { #[no_mangle] pub extern "C" fn InitFeatures_empty() -> InitFeatures { let mut ret = lightning::ln::features::InitFeatures::empty(); - InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a Features with the bits set which are known by the implementation @@ -339,7 +363,7 @@ pub extern "C" fn InitFeatures_empty() -> InitFeatures { #[no_mangle] pub extern "C" fn InitFeatures_known() -> InitFeatures { let mut ret = lightning::ln::features::InitFeatures::known(); - InitFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Create a blank Features with no features set @@ -347,7 +371,7 @@ pub extern "C" fn InitFeatures_known() -> InitFeatures { #[no_mangle] pub extern "C" fn NodeFeatures_empty() -> NodeFeatures { let mut ret = lightning::ln::features::NodeFeatures::empty(); - NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a Features with the bits set which are known by the implementation @@ -355,7 +379,7 @@ pub extern "C" fn NodeFeatures_empty() -> NodeFeatures { #[no_mangle] pub extern "C" fn NodeFeatures_known() -> NodeFeatures { let mut ret = lightning::ln::features::NodeFeatures::known(); - NodeFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Create a blank Features with no features set @@ -363,7 +387,7 @@ pub extern "C" fn NodeFeatures_known() -> NodeFeatures { #[no_mangle] pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures { let mut ret = lightning::ln::features::ChannelFeatures::empty(); - ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a Features with the bits set which are known by the implementation @@ -371,7 +395,7 @@ pub extern "C" fn ChannelFeatures_empty() -> ChannelFeatures { #[no_mangle] pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures { let mut ret = lightning::ln::features::ChannelFeatures::known(); - ChannelFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Create a blank Features with no features set @@ -379,7 +403,7 @@ pub extern "C" fn ChannelFeatures_known() -> ChannelFeatures { #[no_mangle] pub extern "C" fn InvoiceFeatures_empty() -> InvoiceFeatures { let mut ret = lightning::ln::features::InvoiceFeatures::empty(); - InvoiceFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + InvoiceFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a Features with the bits set which are known by the implementation @@ -387,14 +411,14 @@ pub extern "C" fn InvoiceFeatures_empty() -> InvoiceFeatures { #[no_mangle] pub extern "C" fn InvoiceFeatures_known() -> InvoiceFeatures { let mut ret = lightning::ln::features::InvoiceFeatures::known(); - InvoiceFeatures { inner: Box::into_raw(Box::new(ret)), is_owned: true } + InvoiceFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns whether the `payment_secret` feature is supported. #[must_use] #[no_mangle] pub extern "C" fn InitFeatures_supports_payment_secret(this_arg: &InitFeatures) -> bool { - let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret(); ret } @@ -402,7 +426,7 @@ pub extern "C" fn InitFeatures_supports_payment_secret(this_arg: &InitFeatures) #[must_use] #[no_mangle] pub extern "C" fn NodeFeatures_supports_payment_secret(this_arg: &NodeFeatures) -> bool { - let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret(); ret } @@ -410,14 +434,14 @@ pub extern "C" fn NodeFeatures_supports_payment_secret(this_arg: &NodeFeatures) #[must_use] #[no_mangle] pub extern "C" fn InvoiceFeatures_supports_payment_secret(this_arg: &InvoiceFeatures) -> bool { - let mut ret = unsafe { &*this_arg.inner }.supports_payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_payment_secret(); ret } #[no_mangle] /// Serialize the InitFeatures object into a byte array which can be read by InitFeatures_read pub extern "C" fn InitFeatures_write(obj: &InitFeatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -426,7 +450,7 @@ pub(crate) extern "C" fn InitFeatures_write_void(obj: *const c_void) -> crate::c #[no_mangle] /// Serialize the NodeFeatures object into a byte array which can be read by NodeFeatures_read pub extern "C" fn NodeFeatures_write(obj: &NodeFeatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn NodeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -435,7 +459,7 @@ pub(crate) extern "C" fn NodeFeatures_write_void(obj: *const c_void) -> crate::c #[no_mangle] /// Serialize the ChannelFeatures object into a byte array which can be read by ChannelFeatures_read pub extern "C" fn ChannelFeatures_write(obj: &ChannelFeatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -444,7 +468,7 @@ pub(crate) extern "C" fn ChannelFeatures_write_void(obj: *const c_void) -> crate #[no_mangle] /// Serialize the InvoiceFeatures object into a byte array which can be read by InvoiceFeatures_read pub extern "C" fn InvoiceFeatures_write(obj: &InvoiceFeatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn InvoiceFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -454,27 +478,27 @@ pub(crate) extern "C" fn InvoiceFeatures_write_void(obj: *const c_void) -> crate /// Read a InitFeatures from a byte array, created by InitFeatures_write pub extern "C" fn InitFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitFeaturesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::InitFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Read a NodeFeatures from a byte array, created by NodeFeatures_write pub extern "C" fn NodeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeFeaturesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::NodeFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Read a ChannelFeatures from a byte array, created by ChannelFeatures_write pub extern "C" fn ChannelFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelFeaturesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::ChannelFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::ChannelFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Read a InvoiceFeatures from a byte array, created by InvoiceFeatures_write pub extern "C" fn InvoiceFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InvoiceFeaturesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::InvoiceFeatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::InvoiceFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/ln/msgs.rs b/lightning-c-bindings/src/lightning/ln/msgs.rs index cdc862d..b8a2615 100644 --- a/lightning-c-bindings/src/lightning/ln/msgs.rs +++ b/lightning-c-bindings/src/lightning/ln/msgs.rs @@ -51,7 +51,7 @@ pub struct DecodeError { impl Drop for DecodeError { fn drop(&mut self) { if self.is_owned && !<*mut nativeDecodeError>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -64,11 +64,17 @@ extern "C" fn DecodeError_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDecodeError); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl DecodeError { + pub(crate) fn get_native_ref(&self) -> &'static nativeDecodeError { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDecodeError { + 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 nativeDecodeError { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -77,7 +83,7 @@ impl Clone for DecodeError { fn clone(&self) -> Self { Self { inner: if <*mut nativeDecodeError>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -115,7 +121,7 @@ pub struct Init { impl Drop for Init { fn drop(&mut self) { if self.is_owned && !<*mut nativeInit>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -128,11 +134,17 @@ extern "C" fn Init_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInit); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Init { + pub(crate) fn get_native_ref(&self) -> &'static nativeInit { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInit { + 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 nativeInit { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -140,27 +152,27 @@ impl Init { /// The relevant features which the sender supports #[no_mangle] pub extern "C" fn Init_get_features(this_ptr: &Init) -> 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 _) as *mut _) }, is_owned: false } } /// The relevant features which the sender supports #[no_mangle] pub extern "C" fn Init_set_features(this_ptr: &mut Init, 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()) }; } /// Constructs a new Init given each field #[must_use] #[no_mangle] pub extern "C" fn Init_new(mut features_arg: crate::lightning::ln::features::InitFeatures) -> Init { - Init { inner: Box::into_raw(Box::new(nativeInit { + Init { inner: ObjOps::heap_alloc(nativeInit { features: *unsafe { Box::from_raw(features_arg.take_inner()) }, - })), is_owned: true } + }), is_owned: true } } impl Clone for Init { fn clone(&self) -> Self { Self { inner: if <*mut nativeInit>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -198,7 +210,7 @@ pub struct ErrorMessage { impl Drop for ErrorMessage { fn drop(&mut self) { if self.is_owned && !<*mut nativeErrorMessage>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -211,11 +223,17 @@ extern "C" fn ErrorMessage_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeErrorMessage); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ErrorMessage { + pub(crate) fn get_native_ref(&self) -> &'static nativeErrorMessage { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeErrorMessage { + 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 nativeErrorMessage { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -223,13 +241,13 @@ impl ErrorMessage { /// The channel ID involved in the error #[no_mangle] pub extern "C" fn ErrorMessage_get_channel_id(this_ptr: &ErrorMessage) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID involved in the error #[no_mangle] pub extern "C" fn ErrorMessage_set_channel_id(this_ptr: &mut ErrorMessage, 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 = val.data; } /// A possibly human-readable error description. /// The string should be sanitized before it is used (e.g. emitted to logs @@ -237,7 +255,7 @@ pub extern "C" fn ErrorMessage_set_channel_id(this_ptr: &mut ErrorMessage, mut v /// vulnerability in the terminal emulator or the logging subsystem. #[no_mangle] pub extern "C" fn ErrorMessage_get_data(this_ptr: &ErrorMessage) -> crate::c_types::Str { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.data; + let mut inner_val = &mut this_ptr.get_native_mut_ref().data; inner_val.as_str().into() } /// A possibly human-readable error description. @@ -246,22 +264,22 @@ pub extern "C" fn ErrorMessage_get_data(this_ptr: &ErrorMessage) -> crate::c_typ /// vulnerability in the terminal emulator or the logging subsystem. #[no_mangle] pub extern "C" fn ErrorMessage_set_data(this_ptr: &mut ErrorMessage, mut val: crate::c_types::Str) { - unsafe { &mut *this_ptr.inner }.data = val.into_string(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.data = val.into_string(); } /// Constructs a new ErrorMessage given each field #[must_use] #[no_mangle] pub extern "C" fn ErrorMessage_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut data_arg: crate::c_types::Str) -> ErrorMessage { - ErrorMessage { inner: Box::into_raw(Box::new(nativeErrorMessage { + ErrorMessage { inner: ObjOps::heap_alloc(nativeErrorMessage { channel_id: channel_id_arg.data, data: data_arg.into_string(), - })), is_owned: true } + }), is_owned: true } } impl Clone for ErrorMessage { fn clone(&self) -> Self { Self { inner: if <*mut nativeErrorMessage>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -299,7 +317,7 @@ pub struct Ping { impl Drop for Ping { fn drop(&mut self) { if self.is_owned && !<*mut nativePing>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -312,11 +330,17 @@ extern "C" fn Ping_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePing); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Ping { + pub(crate) fn get_native_ref(&self) -> &'static nativePing { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePing { + 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 nativePing { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -324,41 +348,41 @@ impl Ping { /// The desired response length #[no_mangle] pub extern "C" fn Ping_get_ponglen(this_ptr: &Ping) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.ponglen; + let mut inner_val = &mut this_ptr.get_native_mut_ref().ponglen; *inner_val } /// The desired response length #[no_mangle] pub extern "C" fn Ping_set_ponglen(this_ptr: &mut Ping, mut val: u16) { - unsafe { &mut *this_ptr.inner }.ponglen = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.ponglen = val; } /// The ping packet size. /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Ping_get_byteslen(this_ptr: &Ping) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.byteslen; + let mut inner_val = &mut this_ptr.get_native_mut_ref().byteslen; *inner_val } /// The ping packet size. /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Ping_set_byteslen(this_ptr: &mut Ping, mut val: u16) { - unsafe { &mut *this_ptr.inner }.byteslen = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.byteslen = val; } /// Constructs a new Ping given each field #[must_use] #[no_mangle] pub extern "C" fn Ping_new(mut ponglen_arg: u16, mut byteslen_arg: u16) -> Ping { - Ping { inner: Box::into_raw(Box::new(nativePing { + Ping { inner: ObjOps::heap_alloc(nativePing { ponglen: ponglen_arg, byteslen: byteslen_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for Ping { fn clone(&self) -> Self { Self { inner: if <*mut nativePing>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -396,7 +420,7 @@ pub struct Pong { impl Drop for Pong { fn drop(&mut self) { if self.is_owned && !<*mut nativePong>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -409,11 +433,17 @@ extern "C" fn Pong_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePong); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Pong { + pub(crate) fn get_native_ref(&self) -> &'static nativePong { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePong { + 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 nativePong { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -422,28 +452,28 @@ impl Pong { /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Pong_get_byteslen(this_ptr: &Pong) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.byteslen; + let mut inner_val = &mut this_ptr.get_native_mut_ref().byteslen; *inner_val } /// The pong packet size. /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Pong_set_byteslen(this_ptr: &mut Pong, mut val: u16) { - unsafe { &mut *this_ptr.inner }.byteslen = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.byteslen = val; } /// Constructs a new Pong given each field #[must_use] #[no_mangle] pub extern "C" fn Pong_new(mut byteslen_arg: u16) -> Pong { - Pong { inner: Box::into_raw(Box::new(nativePong { + Pong { inner: ObjOps::heap_alloc(nativePong { byteslen: byteslen_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for Pong { fn clone(&self) -> Self { Self { inner: if <*mut nativePong>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -481,7 +511,7 @@ pub struct OpenChannel { impl Drop for OpenChannel { fn drop(&mut self) { if self.is_owned && !<*mut nativeOpenChannel>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -494,11 +524,17 @@ extern "C" fn OpenChannel_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeOpenChannel); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl OpenChannel { + pub(crate) fn get_native_ref(&self) -> &'static nativeOpenChannel { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeOpenChannel { + 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 nativeOpenChannel { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -506,206 +542,206 @@ impl OpenChannel { /// The genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn OpenChannel_get_chain_hash(this_ptr: &OpenChannel) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn OpenChannel_set_chain_hash(this_ptr: &mut OpenChannel, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// A temporary channel ID, until the funding outpoint is announced #[no_mangle] pub extern "C" fn OpenChannel_get_temporary_channel_id(this_ptr: &OpenChannel) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.temporary_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().temporary_channel_id; inner_val } /// A temporary channel ID, until the funding outpoint is announced #[no_mangle] pub extern "C" fn OpenChannel_set_temporary_channel_id(this_ptr: &mut OpenChannel, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.temporary_channel_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.temporary_channel_id = val.data; } /// The channel value #[no_mangle] pub extern "C" fn OpenChannel_get_funding_satoshis(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_satoshis; *inner_val } /// The channel value #[no_mangle] pub extern "C" fn OpenChannel_set_funding_satoshis(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.funding_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_satoshis = val; } /// The amount to push to the counterparty as part of the open, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_get_push_msat(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.push_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().push_msat; *inner_val } /// The amount to push to the counterparty as part of the open, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_set_push_msat(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.push_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.push_msat = val; } /// The threshold below which outputs on transactions broadcast by sender will be omitted #[no_mangle] pub extern "C" fn OpenChannel_get_dust_limit_satoshis(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.dust_limit_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().dust_limit_satoshis; *inner_val } /// The threshold below which outputs on transactions broadcast by sender will be omitted #[no_mangle] pub extern "C" fn OpenChannel_set_dust_limit_satoshis(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.dust_limit_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.dust_limit_satoshis = val; } /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_get_max_htlc_value_in_flight_msat(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_htlc_value_in_flight_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_htlc_value_in_flight_msat; *inner_val } /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_set_max_htlc_value_in_flight_msat(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_htlc_value_in_flight_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_htlc_value_in_flight_msat = val; } /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel #[no_mangle] pub extern "C" fn OpenChannel_get_channel_reserve_satoshis(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_reserve_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_reserve_satoshis; *inner_val } /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel #[no_mangle] pub extern "C" fn OpenChannel_set_channel_reserve_satoshis(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.channel_reserve_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_reserve_satoshis = val; } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_get_htlc_minimum_msat(this_ptr: &OpenChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_minimum_msat; *inner_val } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn OpenChannel_set_htlc_minimum_msat(this_ptr: &mut OpenChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } /// The feerate per 1000-weight of sender generated transactions, until updated by update_fee #[no_mangle] pub extern "C" fn OpenChannel_get_feerate_per_kw(this_ptr: &OpenChannel) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.feerate_per_kw; + let mut inner_val = &mut this_ptr.get_native_mut_ref().feerate_per_kw; *inner_val } /// The feerate per 1000-weight of sender generated transactions, until updated by update_fee #[no_mangle] pub extern "C" fn OpenChannel_set_feerate_per_kw(this_ptr: &mut OpenChannel, mut val: u32) { - unsafe { &mut *this_ptr.inner }.feerate_per_kw = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.feerate_per_kw = val; } /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction #[no_mangle] pub extern "C" fn OpenChannel_get_to_self_delay(this_ptr: &OpenChannel) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.to_self_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().to_self_delay; *inner_val } /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction #[no_mangle] pub extern "C" fn OpenChannel_set_to_self_delay(this_ptr: &mut OpenChannel, mut val: u16) { - unsafe { &mut *this_ptr.inner }.to_self_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.to_self_delay = val; } /// The maximum number of inbound HTLCs towards sender #[no_mangle] pub extern "C" fn OpenChannel_get_max_accepted_htlcs(this_ptr: &OpenChannel) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_accepted_htlcs; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_accepted_htlcs; *inner_val } /// The maximum number of inbound HTLCs towards sender #[no_mangle] pub extern "C" fn OpenChannel_set_max_accepted_htlcs(this_ptr: &mut OpenChannel, mut val: u16) { - unsafe { &mut *this_ptr.inner }.max_accepted_htlcs = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_accepted_htlcs = val; } /// The sender's key controlling the funding transaction #[no_mangle] pub extern "C" fn OpenChannel_get_funding_pubkey(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_pubkey; crate::c_types::PublicKey::from_rust(&inner_val) } /// The sender's key controlling the funding transaction #[no_mangle] pub extern "C" fn OpenChannel_set_funding_pubkey(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.funding_pubkey = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_pubkey = val.into_rust(); } /// Used to derive a revocation key for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn OpenChannel_get_revocation_basepoint(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive a revocation key for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn OpenChannel_set_revocation_basepoint(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.revocation_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_basepoint = val.into_rust(); } /// A payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn OpenChannel_get_payment_point(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// A payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn OpenChannel_set_payment_point(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.payment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_point = val.into_rust(); } /// Used to derive a payment key to sender for transactions broadcast by sender #[no_mangle] pub extern "C" fn OpenChannel_get_delayed_payment_basepoint(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive a payment key to sender for transactions broadcast by sender #[no_mangle] pub extern "C" fn OpenChannel_set_delayed_payment_basepoint(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_basepoint = val.into_rust(); } /// Used to derive an HTLC payment key to sender #[no_mangle] pub extern "C" fn OpenChannel_get_htlc_basepoint(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive an HTLC payment key to sender #[no_mangle] pub extern "C" fn OpenChannel_set_htlc_basepoint(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.htlc_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_basepoint = val.into_rust(); } /// The first to-be-broadcast-by-sender transaction's per commitment point #[no_mangle] pub extern "C" fn OpenChannel_get_first_per_commitment_point(this_ptr: &OpenChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.first_per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().first_per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The first to-be-broadcast-by-sender transaction's per commitment point #[no_mangle] pub extern "C" fn OpenChannel_set_first_per_commitment_point(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.first_per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_per_commitment_point = val.into_rust(); } /// Channel flags #[no_mangle] pub extern "C" fn OpenChannel_get_channel_flags(this_ptr: &OpenChannel) -> u8 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_flags; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_flags; *inner_val } /// Channel flags #[no_mangle] pub extern "C" fn OpenChannel_set_channel_flags(this_ptr: &mut OpenChannel, mut val: u8) { - unsafe { &mut *this_ptr.inner }.channel_flags = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_flags = val; } impl Clone for OpenChannel { fn clone(&self) -> Self { Self { inner: if <*mut nativeOpenChannel>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -743,7 +779,7 @@ pub struct AcceptChannel { impl Drop for AcceptChannel { fn drop(&mut self) { if self.is_owned && !<*mut nativeAcceptChannel>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -756,11 +792,17 @@ extern "C" fn AcceptChannel_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeAcceptChannel); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl AcceptChannel { + pub(crate) fn get_native_ref(&self) -> &'static nativeAcceptChannel { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeAcceptChannel { + 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 nativeAcceptChannel { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -768,162 +810,162 @@ impl AcceptChannel { /// A temporary channel ID, until the funding outpoint is announced #[no_mangle] pub extern "C" fn AcceptChannel_get_temporary_channel_id(this_ptr: &AcceptChannel) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.temporary_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().temporary_channel_id; inner_val } /// A temporary channel ID, until the funding outpoint is announced #[no_mangle] pub extern "C" fn AcceptChannel_set_temporary_channel_id(this_ptr: &mut AcceptChannel, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.temporary_channel_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.temporary_channel_id = val.data; } /// The threshold below which outputs on transactions broadcast by sender will be omitted #[no_mangle] pub extern "C" fn AcceptChannel_get_dust_limit_satoshis(this_ptr: &AcceptChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.dust_limit_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().dust_limit_satoshis; *inner_val } /// The threshold below which outputs on transactions broadcast by sender will be omitted #[no_mangle] pub extern "C" fn AcceptChannel_set_dust_limit_satoshis(this_ptr: &mut AcceptChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.dust_limit_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.dust_limit_satoshis = val; } /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi #[no_mangle] pub extern "C" fn AcceptChannel_get_max_htlc_value_in_flight_msat(this_ptr: &AcceptChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_htlc_value_in_flight_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_htlc_value_in_flight_msat; *inner_val } /// The maximum inbound HTLC value in flight towards sender, in milli-satoshi #[no_mangle] pub extern "C" fn AcceptChannel_set_max_htlc_value_in_flight_msat(this_ptr: &mut AcceptChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_htlc_value_in_flight_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_htlc_value_in_flight_msat = val; } /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel #[no_mangle] pub extern "C" fn AcceptChannel_get_channel_reserve_satoshis(this_ptr: &AcceptChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_reserve_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_reserve_satoshis; *inner_val } /// The minimum value unencumbered by HTLCs for the counterparty to keep in the channel #[no_mangle] pub extern "C" fn AcceptChannel_set_channel_reserve_satoshis(this_ptr: &mut AcceptChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.channel_reserve_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_reserve_satoshis = val; } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn AcceptChannel_get_htlc_minimum_msat(this_ptr: &AcceptChannel) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_minimum_msat; *inner_val } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn AcceptChannel_set_htlc_minimum_msat(this_ptr: &mut AcceptChannel, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } /// Minimum depth of the funding transaction before the channel is considered open #[no_mangle] pub extern "C" fn AcceptChannel_get_minimum_depth(this_ptr: &AcceptChannel) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.minimum_depth; + let mut inner_val = &mut this_ptr.get_native_mut_ref().minimum_depth; *inner_val } /// Minimum depth of the funding transaction before the channel is considered open #[no_mangle] pub extern "C" fn AcceptChannel_set_minimum_depth(this_ptr: &mut AcceptChannel, mut val: u32) { - unsafe { &mut *this_ptr.inner }.minimum_depth = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.minimum_depth = val; } /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction #[no_mangle] pub extern "C" fn AcceptChannel_get_to_self_delay(this_ptr: &AcceptChannel) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.to_self_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().to_self_delay; *inner_val } /// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction #[no_mangle] pub extern "C" fn AcceptChannel_set_to_self_delay(this_ptr: &mut AcceptChannel, mut val: u16) { - unsafe { &mut *this_ptr.inner }.to_self_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.to_self_delay = val; } /// The maximum number of inbound HTLCs towards sender #[no_mangle] pub extern "C" fn AcceptChannel_get_max_accepted_htlcs(this_ptr: &AcceptChannel) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_accepted_htlcs; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_accepted_htlcs; *inner_val } /// The maximum number of inbound HTLCs towards sender #[no_mangle] pub extern "C" fn AcceptChannel_set_max_accepted_htlcs(this_ptr: &mut AcceptChannel, mut val: u16) { - unsafe { &mut *this_ptr.inner }.max_accepted_htlcs = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_accepted_htlcs = val; } /// The sender's key controlling the funding transaction #[no_mangle] pub extern "C" fn AcceptChannel_get_funding_pubkey(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_pubkey; crate::c_types::PublicKey::from_rust(&inner_val) } /// The sender's key controlling the funding transaction #[no_mangle] pub extern "C" fn AcceptChannel_set_funding_pubkey(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.funding_pubkey = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_pubkey = val.into_rust(); } /// Used to derive a revocation key for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_get_revocation_basepoint(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.revocation_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().revocation_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive a revocation key for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_set_revocation_basepoint(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.revocation_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_basepoint = val.into_rust(); } /// A payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_get_payment_point(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// A payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_set_payment_point(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.payment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_point = val.into_rust(); } /// Used to derive a payment key to sender for transactions broadcast by sender #[no_mangle] pub extern "C" fn AcceptChannel_get_delayed_payment_basepoint(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().delayed_payment_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive a payment key to sender for transactions broadcast by sender #[no_mangle] pub extern "C" fn AcceptChannel_set_delayed_payment_basepoint(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.delayed_payment_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.delayed_payment_basepoint = val.into_rust(); } /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_get_htlc_basepoint(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_basepoint; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_basepoint; crate::c_types::PublicKey::from_rust(&inner_val) } /// Used to derive an HTLC payment key to sender for transactions broadcast by counterparty #[no_mangle] pub extern "C" fn AcceptChannel_set_htlc_basepoint(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.htlc_basepoint = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_basepoint = val.into_rust(); } /// The first to-be-broadcast-by-sender transaction's per commitment point #[no_mangle] pub extern "C" fn AcceptChannel_get_first_per_commitment_point(this_ptr: &AcceptChannel) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.first_per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().first_per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The first to-be-broadcast-by-sender transaction's per commitment point #[no_mangle] pub extern "C" fn AcceptChannel_set_first_per_commitment_point(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.first_per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_per_commitment_point = val.into_rust(); } impl Clone for AcceptChannel { fn clone(&self) -> Self { Self { inner: if <*mut nativeAcceptChannel>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -961,7 +1003,7 @@ pub struct FundingCreated { impl Drop for FundingCreated { fn drop(&mut self) { if self.is_owned && !<*mut nativeFundingCreated>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -974,11 +1016,17 @@ extern "C" fn FundingCreated_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFundingCreated); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl FundingCreated { + pub(crate) fn get_native_ref(&self) -> &'static nativeFundingCreated { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFundingCreated { + 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 nativeFundingCreated { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -986,63 +1034,63 @@ impl FundingCreated { /// A temporary channel ID, until the funding is established #[no_mangle] pub extern "C" fn FundingCreated_get_temporary_channel_id(this_ptr: &FundingCreated) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.temporary_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().temporary_channel_id; inner_val } /// A temporary channel ID, until the funding is established #[no_mangle] pub extern "C" fn FundingCreated_set_temporary_channel_id(this_ptr: &mut FundingCreated, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.temporary_channel_id = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.temporary_channel_id = val.data; } /// The funding transaction ID #[no_mangle] pub extern "C" fn FundingCreated_get_funding_txid(this_ptr: &FundingCreated) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_txid; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_txid; inner_val.as_inner() } /// The funding transaction ID #[no_mangle] pub extern "C" fn FundingCreated_set_funding_txid(this_ptr: &mut FundingCreated, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.funding_txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_txid = ::bitcoin::hash_types::Txid::from_slice(&val.data[..]).unwrap(); } /// The specific output index funding this channel #[no_mangle] pub extern "C" fn FundingCreated_get_funding_output_index(this_ptr: &FundingCreated) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.funding_output_index; + let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_output_index; *inner_val } /// The specific output index funding this channel #[no_mangle] pub extern "C" fn FundingCreated_set_funding_output_index(this_ptr: &mut FundingCreated, mut val: u16) { - unsafe { &mut *this_ptr.inner }.funding_output_index = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.funding_output_index = val; } /// The signature of the channel initiator (funder) on the funding transaction #[no_mangle] pub extern "C" fn FundingCreated_get_signature(this_ptr: &FundingCreated) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// The signature of the channel initiator (funder) on the funding transaction #[no_mangle] pub extern "C" fn FundingCreated_set_signature(this_ptr: &mut FundingCreated, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// Constructs a new FundingCreated given each field #[must_use] #[no_mangle] pub extern "C" fn FundingCreated_new(mut temporary_channel_id_arg: crate::c_types::ThirtyTwoBytes, mut funding_txid_arg: crate::c_types::ThirtyTwoBytes, mut funding_output_index_arg: u16, mut signature_arg: crate::c_types::Signature) -> FundingCreated { - FundingCreated { inner: Box::into_raw(Box::new(nativeFundingCreated { + FundingCreated { inner: ObjOps::heap_alloc(nativeFundingCreated { temporary_channel_id: temporary_channel_id_arg.data, funding_txid: ::bitcoin::hash_types::Txid::from_slice(&funding_txid_arg.data[..]).unwrap(), funding_output_index: funding_output_index_arg, signature: signature_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for FundingCreated { fn clone(&self) -> Self { Self { inner: if <*mut nativeFundingCreated>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1080,7 +1128,7 @@ pub struct FundingSigned { impl Drop for FundingSigned { fn drop(&mut self) { if self.is_owned && !<*mut nativeFundingSigned>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1093,11 +1141,17 @@ extern "C" fn FundingSigned_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFundingSigned); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl FundingSigned { + pub(crate) fn get_native_ref(&self) -> &'static nativeFundingSigned { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFundingSigned { + 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 nativeFundingSigned { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1105,39 +1159,39 @@ impl FundingSigned { /// The channel ID #[no_mangle] pub extern "C" fn FundingSigned_get_channel_id(this_ptr: &FundingSigned) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn FundingSigned_set_channel_id(this_ptr: &mut FundingSigned, 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 = val.data; } /// The signature of the channel acceptor (fundee) on the funding transaction #[no_mangle] pub extern "C" fn FundingSigned_get_signature(this_ptr: &FundingSigned) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// The signature of the channel acceptor (fundee) on the funding transaction #[no_mangle] pub extern "C" fn FundingSigned_set_signature(this_ptr: &mut FundingSigned, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// Constructs a new FundingSigned given each field #[must_use] #[no_mangle] pub extern "C" fn FundingSigned_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut signature_arg: crate::c_types::Signature) -> FundingSigned { - FundingSigned { inner: Box::into_raw(Box::new(nativeFundingSigned { + FundingSigned { inner: ObjOps::heap_alloc(nativeFundingSigned { channel_id: channel_id_arg.data, signature: signature_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for FundingSigned { fn clone(&self) -> Self { Self { inner: if <*mut nativeFundingSigned>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1175,7 +1229,7 @@ pub struct FundingLocked { impl Drop for FundingLocked { fn drop(&mut self) { if self.is_owned && !<*mut nativeFundingLocked>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1188,11 +1242,17 @@ extern "C" fn FundingLocked_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFundingLocked); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl FundingLocked { + pub(crate) fn get_native_ref(&self) -> &'static nativeFundingLocked { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFundingLocked { + 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 nativeFundingLocked { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1200,39 +1260,39 @@ impl FundingLocked { /// The channel ID #[no_mangle] pub extern "C" fn FundingLocked_get_channel_id(this_ptr: &FundingLocked) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn FundingLocked_set_channel_id(this_ptr: &mut FundingLocked, 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 = val.data; } /// The per-commitment point of the second commitment transaction #[no_mangle] pub extern "C" fn FundingLocked_get_next_per_commitment_point(this_ptr: &FundingLocked) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.next_per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The per-commitment point of the second commitment transaction #[no_mangle] pub extern "C" fn FundingLocked_set_next_per_commitment_point(this_ptr: &mut FundingLocked, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.next_per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_per_commitment_point = val.into_rust(); } /// Constructs a new FundingLocked given each field #[must_use] #[no_mangle] pub extern "C" fn FundingLocked_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut next_per_commitment_point_arg: crate::c_types::PublicKey) -> FundingLocked { - FundingLocked { inner: Box::into_raw(Box::new(nativeFundingLocked { + FundingLocked { inner: ObjOps::heap_alloc(nativeFundingLocked { channel_id: channel_id_arg.data, next_per_commitment_point: next_per_commitment_point_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for FundingLocked { fn clone(&self) -> Self { Self { inner: if <*mut nativeFundingLocked>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1270,7 +1330,7 @@ pub struct Shutdown { impl Drop for Shutdown { fn drop(&mut self) { if self.is_owned && !<*mut nativeShutdown>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1283,11 +1343,17 @@ extern "C" fn Shutdown_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeShutdown); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Shutdown { + pub(crate) fn get_native_ref(&self) -> &'static nativeShutdown { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeShutdown { + 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 nativeShutdown { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1295,41 +1361,41 @@ impl Shutdown { /// The channel ID #[no_mangle] pub extern "C" fn Shutdown_get_channel_id(this_ptr: &Shutdown) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn Shutdown_set_channel_id(this_ptr: &mut Shutdown, 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 = val.data; } /// The destination of this peer's funds on closing. /// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. #[no_mangle] pub extern "C" fn Shutdown_get_scriptpubkey(this_ptr: &Shutdown) -> crate::c_types::u8slice { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.scriptpubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().scriptpubkey; crate::c_types::u8slice::from_slice(&inner_val[..]) } /// The destination of this peer's funds on closing. /// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. #[no_mangle] pub extern "C" fn Shutdown_set_scriptpubkey(this_ptr: &mut Shutdown, mut val: crate::c_types::derived::CVec_u8Z) { - unsafe { &mut *this_ptr.inner }.scriptpubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust()); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.scriptpubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust()); } /// Constructs a new Shutdown given each field #[must_use] #[no_mangle] pub extern "C" fn Shutdown_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut scriptpubkey_arg: crate::c_types::derived::CVec_u8Z) -> Shutdown { - Shutdown { inner: Box::into_raw(Box::new(nativeShutdown { + Shutdown { inner: ObjOps::heap_alloc(nativeShutdown { channel_id: channel_id_arg.data, scriptpubkey: ::bitcoin::blockdata::script::Script::from(scriptpubkey_arg.into_rust()), - })), is_owned: true } + }), is_owned: true } } impl Clone for Shutdown { fn clone(&self) -> Self { Self { inner: if <*mut nativeShutdown>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1369,7 +1435,7 @@ pub struct ClosingSignedFeeRange { impl Drop for ClosingSignedFeeRange { fn drop(&mut self) { if self.is_owned && !<*mut nativeClosingSignedFeeRange>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1382,11 +1448,17 @@ extern "C" fn ClosingSignedFeeRange_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeClosingSignedFeeRange); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ClosingSignedFeeRange { + pub(crate) fn get_native_ref(&self) -> &'static nativeClosingSignedFeeRange { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeClosingSignedFeeRange { + 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 nativeClosingSignedFeeRange { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1395,42 +1467,42 @@ impl ClosingSignedFeeRange { /// transaction. #[no_mangle] pub extern "C" fn ClosingSignedFeeRange_get_min_fee_satoshis(this_ptr: &ClosingSignedFeeRange) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.min_fee_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().min_fee_satoshis; *inner_val } /// The minimum absolute fee, in satoshis, which the sender is willing to place on the closing /// transaction. #[no_mangle] pub extern "C" fn ClosingSignedFeeRange_set_min_fee_satoshis(this_ptr: &mut ClosingSignedFeeRange, mut val: u64) { - unsafe { &mut *this_ptr.inner }.min_fee_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.min_fee_satoshis = val; } /// The maximum absolute fee, in satoshis, which the sender is willing to place on the closing /// transaction. #[no_mangle] pub extern "C" fn ClosingSignedFeeRange_get_max_fee_satoshis(this_ptr: &ClosingSignedFeeRange) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_fee_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_fee_satoshis; *inner_val } /// The maximum absolute fee, in satoshis, which the sender is willing to place on the closing /// transaction. #[no_mangle] pub extern "C" fn ClosingSignedFeeRange_set_max_fee_satoshis(this_ptr: &mut ClosingSignedFeeRange, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_fee_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_fee_satoshis = val; } /// Constructs a new ClosingSignedFeeRange given each field #[must_use] #[no_mangle] pub extern "C" fn ClosingSignedFeeRange_new(mut min_fee_satoshis_arg: u64, mut max_fee_satoshis_arg: u64) -> ClosingSignedFeeRange { - ClosingSignedFeeRange { inner: Box::into_raw(Box::new(nativeClosingSignedFeeRange { + ClosingSignedFeeRange { inner: ObjOps::heap_alloc(nativeClosingSignedFeeRange { min_fee_satoshis: min_fee_satoshis_arg, max_fee_satoshis: max_fee_satoshis_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ClosingSignedFeeRange { fn clone(&self) -> Self { Self { inner: if <*mut nativeClosingSignedFeeRange>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1468,7 +1540,7 @@ pub struct ClosingSigned { impl Drop for ClosingSigned { fn drop(&mut self) { if self.is_owned && !<*mut nativeClosingSigned>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1481,11 +1553,17 @@ extern "C" fn ClosingSigned_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeClosingSigned); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ClosingSigned { + pub(crate) fn get_native_ref(&self) -> &'static nativeClosingSigned { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeClosingSigned { + 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 nativeClosingSigned { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1493,35 +1571,35 @@ impl ClosingSigned { /// The channel ID #[no_mangle] pub extern "C" fn ClosingSigned_get_channel_id(this_ptr: &ClosingSigned) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn ClosingSigned_set_channel_id(this_ptr: &mut ClosingSigned, 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 = val.data; } /// The proposed total fee for the closing transaction #[no_mangle] pub extern "C" fn ClosingSigned_get_fee_satoshis(this_ptr: &ClosingSigned) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_satoshis; *inner_val } /// The proposed total fee for the closing transaction #[no_mangle] pub extern "C" fn ClosingSigned_set_fee_satoshis(this_ptr: &mut ClosingSigned, mut val: u64) { - unsafe { &mut *this_ptr.inner }.fee_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_satoshis = val; } /// A signature on the closing transaction #[no_mangle] pub extern "C" fn ClosingSigned_get_signature(this_ptr: &ClosingSigned) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// A signature on the closing transaction #[no_mangle] pub extern "C" fn ClosingSigned_set_signature(this_ptr: &mut ClosingSigned, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// The minimum and maximum fees which the sender is willing to accept, provided only by new /// nodes. @@ -1529,8 +1607,8 @@ pub extern "C" fn ClosingSigned_set_signature(this_ptr: &mut ClosingSigned, mut /// 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 ClosingSigned_get_fee_range(this_ptr: &ClosingSigned) -> crate::lightning::ln::msgs::ClosingSignedFeeRange { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_range; - let mut local_inner_val = crate::lightning::ln::msgs::ClosingSignedFeeRange { 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().fee_range; + let mut local_inner_val = crate::lightning::ln::msgs::ClosingSignedFeeRange { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// The minimum and maximum fees which the sender is willing to accept, provided only by new @@ -1540,25 +1618,25 @@ pub extern "C" fn ClosingSigned_get_fee_range(this_ptr: &ClosingSigned) -> crate #[no_mangle] pub extern "C" fn ClosingSigned_set_fee_range(this_ptr: &mut ClosingSigned, mut val: crate::lightning::ln::msgs::ClosingSignedFeeRange) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.fee_range = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_range = local_val; } /// Constructs a new ClosingSigned given each field #[must_use] #[no_mangle] pub extern "C" fn ClosingSigned_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut fee_satoshis_arg: u64, mut signature_arg: crate::c_types::Signature, mut fee_range_arg: crate::lightning::ln::msgs::ClosingSignedFeeRange) -> ClosingSigned { let mut local_fee_range_arg = if fee_range_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(fee_range_arg.take_inner()) } }) }; - ClosingSigned { inner: Box::into_raw(Box::new(nativeClosingSigned { + ClosingSigned { inner: ObjOps::heap_alloc(nativeClosingSigned { channel_id: channel_id_arg.data, fee_satoshis: fee_satoshis_arg, signature: signature_arg.into_rust(), fee_range: local_fee_range_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ClosingSigned { fn clone(&self) -> Self { Self { inner: if <*mut nativeClosingSigned>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1596,7 +1674,7 @@ pub struct UpdateAddHTLC { impl Drop for UpdateAddHTLC { fn drop(&mut self) { if self.is_owned && !<*mut nativeUpdateAddHTLC>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1609,11 +1687,17 @@ extern "C" fn UpdateAddHTLC_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUpdateAddHTLC); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UpdateAddHTLC { + pub(crate) fn get_native_ref(&self) -> &'static nativeUpdateAddHTLC { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUpdateAddHTLC { + 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 nativeUpdateAddHTLC { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1621,63 +1705,63 @@ impl UpdateAddHTLC { /// The channel ID #[no_mangle] pub extern "C" fn UpdateAddHTLC_get_channel_id(this_ptr: &UpdateAddHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_channel_id(this_ptr: &mut UpdateAddHTLC, 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 = val.data; } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateAddHTLC_get_htlc_id(this_ptr: &UpdateAddHTLC) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_id; *inner_val } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_htlc_id(this_ptr: &mut UpdateAddHTLC, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_id = val; } /// The HTLC value in milli-satoshi #[no_mangle] pub extern "C" fn UpdateAddHTLC_get_amount_msat(this_ptr: &UpdateAddHTLC) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.amount_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat; *inner_val } /// The HTLC value in milli-satoshi #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_amount_msat(this_ptr: &mut UpdateAddHTLC, mut val: u64) { - unsafe { &mut *this_ptr.inner }.amount_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val; } /// The payment hash, the pre-image of which controls HTLC redemption #[no_mangle] pub extern "C" fn UpdateAddHTLC_get_payment_hash(this_ptr: &UpdateAddHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_hash; &inner_val.0 } /// The payment hash, the pre-image of which controls HTLC redemption #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_payment_hash(this_ptr: &mut UpdateAddHTLC, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_hash = ::lightning::ln::PaymentHash(val.data); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_hash = ::lightning::ln::PaymentHash(val.data); } /// The expiry height of the HTLC #[no_mangle] pub extern "C" fn UpdateAddHTLC_get_cltv_expiry(this_ptr: &UpdateAddHTLC) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry; *inner_val } /// The expiry height of the HTLC #[no_mangle] pub extern "C" fn UpdateAddHTLC_set_cltv_expiry(this_ptr: &mut UpdateAddHTLC, mut val: u32) { - unsafe { &mut *this_ptr.inner }.cltv_expiry = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry = val; } impl Clone for UpdateAddHTLC { fn clone(&self) -> Self { Self { inner: if <*mut nativeUpdateAddHTLC>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1715,7 +1799,7 @@ pub struct UpdateFulfillHTLC { impl Drop for UpdateFulfillHTLC { fn drop(&mut self) { if self.is_owned && !<*mut nativeUpdateFulfillHTLC>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1728,11 +1812,17 @@ extern "C" fn UpdateFulfillHTLC_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUpdateFulfillHTLC); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UpdateFulfillHTLC { + pub(crate) fn get_native_ref(&self) -> &'static nativeUpdateFulfillHTLC { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUpdateFulfillHTLC { + 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 nativeUpdateFulfillHTLC { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1740,51 +1830,51 @@ impl UpdateFulfillHTLC { /// The channel ID #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_get_channel_id(this_ptr: &UpdateFulfillHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_set_channel_id(this_ptr: &mut UpdateFulfillHTLC, 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 = val.data; } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_get_htlc_id(this_ptr: &UpdateFulfillHTLC) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_id; *inner_val } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_set_htlc_id(this_ptr: &mut UpdateFulfillHTLC, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_id = val; } /// The pre-image of the payment hash, allowing HTLC redemption #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_get_payment_preimage(this_ptr: &UpdateFulfillHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.payment_preimage; + let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_preimage; &inner_val.0 } /// The pre-image of the payment hash, allowing HTLC redemption #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_set_payment_preimage(this_ptr: &mut UpdateFulfillHTLC, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.payment_preimage = ::lightning::ln::PaymentPreimage(val.data); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_preimage = ::lightning::ln::PaymentPreimage(val.data); } /// Constructs a new UpdateFulfillHTLC given each field #[must_use] #[no_mangle] pub extern "C" fn UpdateFulfillHTLC_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut htlc_id_arg: u64, mut payment_preimage_arg: crate::c_types::ThirtyTwoBytes) -> UpdateFulfillHTLC { - UpdateFulfillHTLC { inner: Box::into_raw(Box::new(nativeUpdateFulfillHTLC { + UpdateFulfillHTLC { inner: ObjOps::heap_alloc(nativeUpdateFulfillHTLC { channel_id: channel_id_arg.data, htlc_id: htlc_id_arg, payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage_arg.data), - })), is_owned: true } + }), is_owned: true } } impl Clone for UpdateFulfillHTLC { fn clone(&self) -> Self { Self { inner: if <*mut nativeUpdateFulfillHTLC>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1822,7 +1912,7 @@ pub struct UpdateFailHTLC { impl Drop for UpdateFailHTLC { fn drop(&mut self) { if self.is_owned && !<*mut nativeUpdateFailHTLC>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1835,11 +1925,17 @@ extern "C" fn UpdateFailHTLC_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUpdateFailHTLC); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UpdateFailHTLC { + pub(crate) fn get_native_ref(&self) -> &'static nativeUpdateFailHTLC { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUpdateFailHTLC { + 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 nativeUpdateFailHTLC { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1847,30 +1943,30 @@ impl UpdateFailHTLC { /// The channel ID #[no_mangle] pub extern "C" fn UpdateFailHTLC_get_channel_id(this_ptr: &UpdateFailHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn UpdateFailHTLC_set_channel_id(this_ptr: &mut UpdateFailHTLC, 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 = val.data; } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFailHTLC_get_htlc_id(this_ptr: &UpdateFailHTLC) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_id; *inner_val } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFailHTLC_set_htlc_id(this_ptr: &mut UpdateFailHTLC, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_id = val; } impl Clone for UpdateFailHTLC { fn clone(&self) -> Self { Self { inner: if <*mut nativeUpdateFailHTLC>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1908,7 +2004,7 @@ pub struct UpdateFailMalformedHTLC { impl Drop for UpdateFailMalformedHTLC { fn drop(&mut self) { if self.is_owned && !<*mut nativeUpdateFailMalformedHTLC>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1921,11 +2017,17 @@ extern "C" fn UpdateFailMalformedHTLC_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUpdateFailMalformedHTLC); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UpdateFailMalformedHTLC { + pub(crate) fn get_native_ref(&self) -> &'static nativeUpdateFailMalformedHTLC { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUpdateFailMalformedHTLC { + 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 nativeUpdateFailMalformedHTLC { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1933,41 +2035,41 @@ impl UpdateFailMalformedHTLC { /// The channel ID #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_get_channel_id(this_ptr: &UpdateFailMalformedHTLC) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_set_channel_id(this_ptr: &mut UpdateFailMalformedHTLC, 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 = val.data; } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_get_htlc_id(this_ptr: &UpdateFailMalformedHTLC) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_id; *inner_val } /// The HTLC ID #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_set_htlc_id(this_ptr: &mut UpdateFailMalformedHTLC, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_id = val; } /// The failure code #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_get_failure_code(this_ptr: &UpdateFailMalformedHTLC) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.failure_code; + let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_code; *inner_val } /// The failure code #[no_mangle] pub extern "C" fn UpdateFailMalformedHTLC_set_failure_code(this_ptr: &mut UpdateFailMalformedHTLC, mut val: u16) { - unsafe { &mut *this_ptr.inner }.failure_code = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_code = val; } impl Clone for UpdateFailMalformedHTLC { fn clone(&self) -> Self { Self { inner: if <*mut nativeUpdateFailMalformedHTLC>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2005,7 +2107,7 @@ pub struct CommitmentSigned { impl Drop for CommitmentSigned { fn drop(&mut self) { if self.is_owned && !<*mut nativeCommitmentSigned>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2018,11 +2120,17 @@ extern "C" fn CommitmentSigned_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCommitmentSigned); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl CommitmentSigned { + pub(crate) fn get_native_ref(&self) -> &'static nativeCommitmentSigned { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCommitmentSigned { + 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 nativeCommitmentSigned { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2030,47 +2138,47 @@ impl CommitmentSigned { /// The channel ID #[no_mangle] pub extern "C" fn CommitmentSigned_get_channel_id(this_ptr: &CommitmentSigned) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn CommitmentSigned_set_channel_id(this_ptr: &mut CommitmentSigned, 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 = val.data; } /// A signature on the commitment transaction #[no_mangle] pub extern "C" fn CommitmentSigned_get_signature(this_ptr: &CommitmentSigned) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// A signature on the commitment transaction #[no_mangle] pub extern "C" fn CommitmentSigned_set_signature(this_ptr: &mut CommitmentSigned, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// Signatures on the HTLC transactions #[no_mangle] pub extern "C" fn CommitmentSigned_set_htlc_signatures(this_ptr: &mut CommitmentSigned, mut val: crate::c_types::derived::CVec_SignatureZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_rust() }); }; - unsafe { &mut *this_ptr.inner }.htlc_signatures = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_signatures = local_val; } /// Constructs a new CommitmentSigned given each field #[must_use] #[no_mangle] pub extern "C" fn CommitmentSigned_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut signature_arg: crate::c_types::Signature, mut htlc_signatures_arg: crate::c_types::derived::CVec_SignatureZ) -> CommitmentSigned { let mut local_htlc_signatures_arg = Vec::new(); for mut item in htlc_signatures_arg.into_rust().drain(..) { local_htlc_signatures_arg.push( { item.into_rust() }); }; - CommitmentSigned { inner: Box::into_raw(Box::new(nativeCommitmentSigned { + CommitmentSigned { inner: ObjOps::heap_alloc(nativeCommitmentSigned { channel_id: channel_id_arg.data, signature: signature_arg.into_rust(), htlc_signatures: local_htlc_signatures_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for CommitmentSigned { fn clone(&self) -> Self { Self { inner: if <*mut nativeCommitmentSigned>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2108,7 +2216,7 @@ pub struct RevokeAndACK { impl Drop for RevokeAndACK { fn drop(&mut self) { if self.is_owned && !<*mut nativeRevokeAndACK>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2121,11 +2229,17 @@ extern "C" fn RevokeAndACK_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRevokeAndACK); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RevokeAndACK { + pub(crate) fn get_native_ref(&self) -> &'static nativeRevokeAndACK { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRevokeAndACK { + 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 nativeRevokeAndACK { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2133,51 +2247,51 @@ impl RevokeAndACK { /// The channel ID #[no_mangle] pub extern "C" fn RevokeAndACK_get_channel_id(this_ptr: &RevokeAndACK) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn RevokeAndACK_set_channel_id(this_ptr: &mut RevokeAndACK, 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 = val.data; } /// The secret corresponding to the per-commitment point #[no_mangle] pub extern "C" fn RevokeAndACK_get_per_commitment_secret(this_ptr: &RevokeAndACK) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.per_commitment_secret; + let mut inner_val = &mut this_ptr.get_native_mut_ref().per_commitment_secret; inner_val } /// The secret corresponding to the per-commitment point #[no_mangle] pub extern "C" fn RevokeAndACK_set_per_commitment_secret(this_ptr: &mut RevokeAndACK, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.per_commitment_secret = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.per_commitment_secret = val.data; } /// The next sender-broadcast commitment transaction's per-commitment point #[no_mangle] pub extern "C" fn RevokeAndACK_get_next_per_commitment_point(this_ptr: &RevokeAndACK) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.next_per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The next sender-broadcast commitment transaction's per-commitment point #[no_mangle] pub extern "C" fn RevokeAndACK_set_next_per_commitment_point(this_ptr: &mut RevokeAndACK, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.next_per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_per_commitment_point = val.into_rust(); } /// Constructs a new RevokeAndACK given each field #[must_use] #[no_mangle] pub extern "C" fn RevokeAndACK_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut per_commitment_secret_arg: crate::c_types::ThirtyTwoBytes, mut next_per_commitment_point_arg: crate::c_types::PublicKey) -> RevokeAndACK { - RevokeAndACK { inner: Box::into_raw(Box::new(nativeRevokeAndACK { + RevokeAndACK { inner: ObjOps::heap_alloc(nativeRevokeAndACK { channel_id: channel_id_arg.data, per_commitment_secret: per_commitment_secret_arg.data, next_per_commitment_point: next_per_commitment_point_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for RevokeAndACK { fn clone(&self) -> Self { Self { inner: if <*mut nativeRevokeAndACK>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2215,7 +2329,7 @@ pub struct UpdateFee { impl Drop for UpdateFee { fn drop(&mut self) { if self.is_owned && !<*mut nativeUpdateFee>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2228,11 +2342,17 @@ extern "C" fn UpdateFee_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUpdateFee); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UpdateFee { + pub(crate) fn get_native_ref(&self) -> &'static nativeUpdateFee { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUpdateFee { + 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 nativeUpdateFee { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2240,39 +2360,39 @@ impl UpdateFee { /// The channel ID #[no_mangle] pub extern "C" fn UpdateFee_get_channel_id(this_ptr: &UpdateFee) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn UpdateFee_set_channel_id(this_ptr: &mut UpdateFee, 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 = val.data; } /// Fee rate per 1000-weight of the transaction #[no_mangle] pub extern "C" fn UpdateFee_get_feerate_per_kw(this_ptr: &UpdateFee) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.feerate_per_kw; + let mut inner_val = &mut this_ptr.get_native_mut_ref().feerate_per_kw; *inner_val } /// Fee rate per 1000-weight of the transaction #[no_mangle] pub extern "C" fn UpdateFee_set_feerate_per_kw(this_ptr: &mut UpdateFee, mut val: u32) { - unsafe { &mut *this_ptr.inner }.feerate_per_kw = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.feerate_per_kw = val; } /// Constructs a new UpdateFee given each field #[must_use] #[no_mangle] pub extern "C" fn UpdateFee_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut feerate_per_kw_arg: u32) -> UpdateFee { - UpdateFee { inner: Box::into_raw(Box::new(nativeUpdateFee { + UpdateFee { inner: ObjOps::heap_alloc(nativeUpdateFee { channel_id: channel_id_arg.data, feerate_per_kw: feerate_per_kw_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for UpdateFee { fn clone(&self) -> Self { Self { inner: if <*mut nativeUpdateFee>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2313,7 +2433,7 @@ pub struct DataLossProtect { impl Drop for DataLossProtect { fn drop(&mut self) { if self.is_owned && !<*mut nativeDataLossProtect>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2326,11 +2446,17 @@ extern "C" fn DataLossProtect_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDataLossProtect); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl DataLossProtect { + pub(crate) fn get_native_ref(&self) -> &'static nativeDataLossProtect { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDataLossProtect { + 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 nativeDataLossProtect { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2339,40 +2465,40 @@ impl DataLossProtect { /// belonging to the recipient #[no_mangle] pub extern "C" fn DataLossProtect_get_your_last_per_commitment_secret(this_ptr: &DataLossProtect) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.your_last_per_commitment_secret; + let mut inner_val = &mut this_ptr.get_native_mut_ref().your_last_per_commitment_secret; inner_val } /// Proof that the sender knows the per-commitment secret of a specific commitment transaction /// belonging to the recipient #[no_mangle] pub extern "C" fn DataLossProtect_set_your_last_per_commitment_secret(this_ptr: &mut DataLossProtect, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.your_last_per_commitment_secret = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.your_last_per_commitment_secret = val.data; } /// The sender's per-commitment point for their current commitment transaction #[no_mangle] pub extern "C" fn DataLossProtect_get_my_current_per_commitment_point(this_ptr: &DataLossProtect) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.my_current_per_commitment_point; + let mut inner_val = &mut this_ptr.get_native_mut_ref().my_current_per_commitment_point; crate::c_types::PublicKey::from_rust(&inner_val) } /// The sender's per-commitment point for their current commitment transaction #[no_mangle] pub extern "C" fn DataLossProtect_set_my_current_per_commitment_point(this_ptr: &mut DataLossProtect, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.my_current_per_commitment_point = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.my_current_per_commitment_point = val.into_rust(); } /// Constructs a new DataLossProtect given each field #[must_use] #[no_mangle] pub extern "C" fn DataLossProtect_new(mut your_last_per_commitment_secret_arg: crate::c_types::ThirtyTwoBytes, mut my_current_per_commitment_point_arg: crate::c_types::PublicKey) -> DataLossProtect { - DataLossProtect { inner: Box::into_raw(Box::new(nativeDataLossProtect { + DataLossProtect { inner: ObjOps::heap_alloc(nativeDataLossProtect { your_last_per_commitment_secret: your_last_per_commitment_secret_arg.data, my_current_per_commitment_point: my_current_per_commitment_point_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for DataLossProtect { fn clone(&self) -> Self { Self { inner: if <*mut nativeDataLossProtect>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2410,7 +2536,7 @@ pub struct ChannelReestablish { impl Drop for ChannelReestablish { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelReestablish>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2423,11 +2549,17 @@ extern "C" fn ChannelReestablish_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelReestablish); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelReestablish { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelReestablish { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelReestablish { + 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 nativeChannelReestablish { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2435,41 +2567,41 @@ impl ChannelReestablish { /// The channel ID #[no_mangle] pub extern "C" fn ChannelReestablish_get_channel_id(this_ptr: &ChannelReestablish) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn ChannelReestablish_set_channel_id(this_ptr: &mut ChannelReestablish, 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 = val.data; } /// The next commitment number for the sender #[no_mangle] pub extern "C" fn ChannelReestablish_get_next_local_commitment_number(this_ptr: &ChannelReestablish) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.next_local_commitment_number; + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_local_commitment_number; *inner_val } /// The next commitment number for the sender #[no_mangle] pub extern "C" fn ChannelReestablish_set_next_local_commitment_number(this_ptr: &mut ChannelReestablish, mut val: u64) { - unsafe { &mut *this_ptr.inner }.next_local_commitment_number = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_local_commitment_number = val; } /// The next commitment number for the recipient #[no_mangle] pub extern "C" fn ChannelReestablish_get_next_remote_commitment_number(this_ptr: &ChannelReestablish) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.next_remote_commitment_number; + let mut inner_val = &mut this_ptr.get_native_mut_ref().next_remote_commitment_number; *inner_val } /// The next commitment number for the recipient #[no_mangle] pub extern "C" fn ChannelReestablish_set_next_remote_commitment_number(this_ptr: &mut ChannelReestablish, mut val: u64) { - unsafe { &mut *this_ptr.inner }.next_remote_commitment_number = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_remote_commitment_number = val; } impl Clone for ChannelReestablish { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelReestablish>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2507,7 +2639,7 @@ pub struct AnnouncementSignatures { impl Drop for AnnouncementSignatures { fn drop(&mut self) { if self.is_owned && !<*mut nativeAnnouncementSignatures>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2520,11 +2652,17 @@ extern "C" fn AnnouncementSignatures_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeAnnouncementSignatures); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl AnnouncementSignatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeAnnouncementSignatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeAnnouncementSignatures { + 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 nativeAnnouncementSignatures { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2532,63 +2670,63 @@ impl AnnouncementSignatures { /// The channel ID #[no_mangle] pub extern "C" fn AnnouncementSignatures_get_channel_id(this_ptr: &AnnouncementSignatures) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_id; inner_val } /// The channel ID #[no_mangle] pub extern "C" fn AnnouncementSignatures_set_channel_id(this_ptr: &mut AnnouncementSignatures, 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 = val.data; } /// The short channel ID #[no_mangle] pub extern "C" fn AnnouncementSignatures_get_short_channel_id(this_ptr: &AnnouncementSignatures) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; *inner_val } /// The short channel ID #[no_mangle] pub extern "C" fn AnnouncementSignatures_set_short_channel_id(this_ptr: &mut AnnouncementSignatures, mut val: u64) { - unsafe { &mut *this_ptr.inner }.short_channel_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } /// A signature by the node key #[no_mangle] pub extern "C" fn AnnouncementSignatures_get_node_signature(this_ptr: &AnnouncementSignatures) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signature; crate::c_types::Signature::from_rust(&inner_val) } /// A signature by the node key #[no_mangle] pub extern "C" fn AnnouncementSignatures_set_node_signature(this_ptr: &mut AnnouncementSignatures, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.node_signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signature = val.into_rust(); } /// A signature by the funding key #[no_mangle] pub extern "C" fn AnnouncementSignatures_get_bitcoin_signature(this_ptr: &AnnouncementSignatures) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.bitcoin_signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_signature; crate::c_types::Signature::from_rust(&inner_val) } /// A signature by the funding key #[no_mangle] pub extern "C" fn AnnouncementSignatures_set_bitcoin_signature(this_ptr: &mut AnnouncementSignatures, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.bitcoin_signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_signature = val.into_rust(); } /// Constructs a new AnnouncementSignatures given each field #[must_use] #[no_mangle] pub extern "C" fn AnnouncementSignatures_new(mut channel_id_arg: crate::c_types::ThirtyTwoBytes, mut short_channel_id_arg: u64, mut node_signature_arg: crate::c_types::Signature, mut bitcoin_signature_arg: crate::c_types::Signature) -> AnnouncementSignatures { - AnnouncementSignatures { inner: Box::into_raw(Box::new(nativeAnnouncementSignatures { + AnnouncementSignatures { inner: ObjOps::heap_alloc(nativeAnnouncementSignatures { channel_id: channel_id_arg.data, short_channel_id: short_channel_id_arg, node_signature: node_signature_arg.into_rust(), bitcoin_signature: bitcoin_signature_arg.into_rust(), - })), is_owned: true } + }), is_owned: true } } impl Clone for AnnouncementSignatures { fn clone(&self) -> Self { Self { inner: if <*mut nativeAnnouncementSignatures>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -2841,14 +2979,14 @@ pub extern "C" fn NetAddress_write(obj: &NetAddress) -> crate::c_types::derived: /// Read a Result from a byte array, created by Result_write pub extern "C" fn Result_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CResult_NetAddressu8ZDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = match o { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NetAddress::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { e }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = match o { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NetAddress::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { e }).into() }; local_res_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_res } #[no_mangle] /// Read a NetAddress from a byte array, created by NetAddress_write pub extern "C" fn NetAddress_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NetAddressDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NetAddress::native_into(o) }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NetAddress::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -2874,7 +3012,7 @@ pub struct UnsignedNodeAnnouncement { impl Drop for UnsignedNodeAnnouncement { fn drop(&mut self) { if self.is_owned && !<*mut nativeUnsignedNodeAnnouncement>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -2887,11 +3025,17 @@ extern "C" fn UnsignedNodeAnnouncement_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUnsignedNodeAnnouncement); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UnsignedNodeAnnouncement { + pub(crate) fn get_native_ref(&self) -> &'static nativeUnsignedNodeAnnouncement { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUnsignedNodeAnnouncement { + 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 nativeUnsignedNodeAnnouncement { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -2899,73 +3043,73 @@ impl UnsignedNodeAnnouncement { /// The advertised features #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_features(this_ptr: &UnsignedNodeAnnouncement) -> crate::lightning::ln::features::NodeFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features; - crate::lightning::ln::features::NodeFeatures { 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::NodeFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The advertised features #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_features(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::lightning::ln::features::NodeFeatures) { - 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()) }; } /// A strictly monotonic announcement counter, with gaps allowed #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_timestamp(this_ptr: &UnsignedNodeAnnouncement) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.timestamp; + let mut inner_val = &mut this_ptr.get_native_mut_ref().timestamp; *inner_val } /// A strictly monotonic announcement counter, with gaps allowed #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_timestamp(this_ptr: &mut UnsignedNodeAnnouncement, mut val: u32) { - unsafe { &mut *this_ptr.inner }.timestamp = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp = val; } /// The node_id this announcement originated from (don't rebroadcast the node_announcement back /// to this node). #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_node_id(this_ptr: &UnsignedNodeAnnouncement) -> 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 this announcement originated from (don't rebroadcast the node_announcement back /// to this node). #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_node_id(this_ptr: &mut UnsignedNodeAnnouncement, 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(); } /// An RGB color for UI purposes #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_rgb(this_ptr: &UnsignedNodeAnnouncement) -> *const [u8; 3] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.rgb; + let mut inner_val = &mut this_ptr.get_native_mut_ref().rgb; inner_val } /// An RGB color for UI purposes #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_rgb(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::ThreeBytes) { - unsafe { &mut *this_ptr.inner }.rgb = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.rgb = val.data; } /// An alias, for UI purposes. This should be sanitized before use. There is no guarantee /// of uniqueness. #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_alias(this_ptr: &UnsignedNodeAnnouncement) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.alias; + let mut inner_val = &mut this_ptr.get_native_mut_ref().alias; inner_val } /// An alias, for UI purposes. This should be sanitized before use. There is no guarantee /// of uniqueness. #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_alias(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.alias = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.alias = val.data; } /// List of addresses on which this node is reachable #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_addresses(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::derived::CVec_NetAddressZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_native() }); }; - unsafe { &mut *this_ptr.inner }.addresses = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.addresses = local_val; } impl Clone for UnsignedNodeAnnouncement { fn clone(&self) -> Self { Self { inner: if <*mut nativeUnsignedNodeAnnouncement>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3003,7 +3147,7 @@ pub struct NodeAnnouncement { impl Drop for NodeAnnouncement { fn drop(&mut self) { if self.is_owned && !<*mut nativeNodeAnnouncement>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3016,11 +3160,17 @@ extern "C" fn NodeAnnouncement_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNodeAnnouncement); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NodeAnnouncement { + pub(crate) fn get_native_ref(&self) -> &'static nativeNodeAnnouncement { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNodeAnnouncement { + 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 nativeNodeAnnouncement { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3028,39 +3178,39 @@ impl NodeAnnouncement { /// The signature by the node key #[no_mangle] pub extern "C" fn NodeAnnouncement_get_signature(this_ptr: &NodeAnnouncement) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// The signature by the node key #[no_mangle] pub extern "C" fn NodeAnnouncement_set_signature(this_ptr: &mut NodeAnnouncement, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// The actual content of the announcement #[no_mangle] pub extern "C" fn NodeAnnouncement_get_contents(this_ptr: &NodeAnnouncement) -> crate::lightning::ln::msgs::UnsignedNodeAnnouncement { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.contents; - crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().contents; + crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The actual content of the announcement #[no_mangle] pub extern "C" fn NodeAnnouncement_set_contents(this_ptr: &mut NodeAnnouncement, mut val: crate::lightning::ln::msgs::UnsignedNodeAnnouncement) { - unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.contents = *unsafe { Box::from_raw(val.take_inner()) }; } /// Constructs a new NodeAnnouncement given each field #[must_use] #[no_mangle] pub extern "C" fn NodeAnnouncement_new(mut signature_arg: crate::c_types::Signature, mut contents_arg: crate::lightning::ln::msgs::UnsignedNodeAnnouncement) -> NodeAnnouncement { - NodeAnnouncement { inner: Box::into_raw(Box::new(nativeNodeAnnouncement { + NodeAnnouncement { inner: ObjOps::heap_alloc(nativeNodeAnnouncement { signature: signature_arg.into_rust(), contents: *unsafe { Box::from_raw(contents_arg.take_inner()) }, - })), is_owned: true } + }), is_owned: true } } impl Clone for NodeAnnouncement { fn clone(&self) -> Self { Self { inner: if <*mut nativeNodeAnnouncement>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3098,7 +3248,7 @@ pub struct UnsignedChannelAnnouncement { impl Drop for UnsignedChannelAnnouncement { fn drop(&mut self) { if self.is_owned && !<*mut nativeUnsignedChannelAnnouncement>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3111,11 +3261,17 @@ extern "C" fn UnsignedChannelAnnouncement_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUnsignedChannelAnnouncement); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UnsignedChannelAnnouncement { + pub(crate) fn get_native_ref(&self) -> &'static nativeUnsignedChannelAnnouncement { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUnsignedChannelAnnouncement { + 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 nativeUnsignedChannelAnnouncement { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3123,85 +3279,85 @@ impl UnsignedChannelAnnouncement { /// The advertised channel features #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_features(this_ptr: &UnsignedChannelAnnouncement) -> crate::lightning::ln::features::ChannelFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features; - crate::lightning::ln::features::ChannelFeatures { 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::ChannelFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The advertised channel features #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_features(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::lightning::ln::features::ChannelFeatures) { - 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 genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_chain_hash(this_ptr: &UnsignedChannelAnnouncement) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_chain_hash(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The short channel ID #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_short_channel_id(this_ptr: &UnsignedChannelAnnouncement) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; *inner_val } /// The short channel ID #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_short_channel_id(this_ptr: &mut UnsignedChannelAnnouncement, mut val: u64) { - unsafe { &mut *this_ptr.inner }.short_channel_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } /// One of the two node_ids which are endpoints of this channel #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_id_1; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id_1; crate::c_types::PublicKey::from_rust(&inner_val) } /// One of the two node_ids which are endpoints of this channel #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.node_id_1 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_1 = val.into_rust(); } /// The other of the two node_ids which are endpoints of this channel #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_id_2; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id_2; crate::c_types::PublicKey::from_rust(&inner_val) } /// The other of the two node_ids which are endpoints of this channel #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.node_id_2 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_2 = val.into_rust(); } /// The funding key for the first node #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.bitcoin_key_1; + let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_key_1; crate::c_types::PublicKey::from_rust(&inner_val) } /// The funding key for the first node #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.bitcoin_key_1 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_1 = val.into_rust(); } /// The funding key for the second node #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.bitcoin_key_2; + let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_key_2; crate::c_types::PublicKey::from_rust(&inner_val) } /// The funding key for the second node #[no_mangle] pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.bitcoin_key_2 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_2 = val.into_rust(); } impl Clone for UnsignedChannelAnnouncement { fn clone(&self) -> Self { Self { inner: if <*mut nativeUnsignedChannelAnnouncement>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3239,7 +3395,7 @@ pub struct ChannelAnnouncement { impl Drop for ChannelAnnouncement { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelAnnouncement>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3252,11 +3408,17 @@ extern "C" fn ChannelAnnouncement_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelAnnouncement); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelAnnouncement { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelAnnouncement { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelAnnouncement { + 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 nativeChannelAnnouncement { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3264,75 +3426,75 @@ impl ChannelAnnouncement { /// Authentication of the announcement by the first public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_get_node_signature_1(this_ptr: &ChannelAnnouncement) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_signature_1; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signature_1; crate::c_types::Signature::from_rust(&inner_val) } /// Authentication of the announcement by the first public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_set_node_signature_1(this_ptr: &mut ChannelAnnouncement, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.node_signature_1 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signature_1 = val.into_rust(); } /// Authentication of the announcement by the second public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_get_node_signature_2(this_ptr: &ChannelAnnouncement) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_signature_2; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signature_2; crate::c_types::Signature::from_rust(&inner_val) } /// Authentication of the announcement by the second public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_set_node_signature_2(this_ptr: &mut ChannelAnnouncement, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.node_signature_2 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signature_2 = val.into_rust(); } /// Proof of funding UTXO ownership by the first public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_get_bitcoin_signature_1(this_ptr: &ChannelAnnouncement) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.bitcoin_signature_1; + let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_signature_1; crate::c_types::Signature::from_rust(&inner_val) } /// Proof of funding UTXO ownership by the first public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_set_bitcoin_signature_1(this_ptr: &mut ChannelAnnouncement, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.bitcoin_signature_1 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_signature_1 = val.into_rust(); } /// Proof of funding UTXO ownership by the second public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_get_bitcoin_signature_2(this_ptr: &ChannelAnnouncement) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.bitcoin_signature_2; + let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_signature_2; crate::c_types::Signature::from_rust(&inner_val) } /// Proof of funding UTXO ownership by the second public node #[no_mangle] pub extern "C" fn ChannelAnnouncement_set_bitcoin_signature_2(this_ptr: &mut ChannelAnnouncement, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.bitcoin_signature_2 = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_signature_2 = val.into_rust(); } /// The actual announcement #[no_mangle] pub extern "C" fn ChannelAnnouncement_get_contents(this_ptr: &ChannelAnnouncement) -> crate::lightning::ln::msgs::UnsignedChannelAnnouncement { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.contents; - crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().contents; + crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The actual announcement #[no_mangle] pub extern "C" fn ChannelAnnouncement_set_contents(this_ptr: &mut ChannelAnnouncement, mut val: crate::lightning::ln::msgs::UnsignedChannelAnnouncement) { - unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.contents = *unsafe { Box::from_raw(val.take_inner()) }; } /// Constructs a new ChannelAnnouncement given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelAnnouncement_new(mut node_signature_1_arg: crate::c_types::Signature, mut node_signature_2_arg: crate::c_types::Signature, mut bitcoin_signature_1_arg: crate::c_types::Signature, mut bitcoin_signature_2_arg: crate::c_types::Signature, mut contents_arg: crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> ChannelAnnouncement { - ChannelAnnouncement { inner: Box::into_raw(Box::new(nativeChannelAnnouncement { + ChannelAnnouncement { inner: ObjOps::heap_alloc(nativeChannelAnnouncement { node_signature_1: node_signature_1_arg.into_rust(), node_signature_2: node_signature_2_arg.into_rust(), bitcoin_signature_1: bitcoin_signature_1_arg.into_rust(), bitcoin_signature_2: bitcoin_signature_2_arg.into_rust(), contents: *unsafe { Box::from_raw(contents_arg.take_inner()) }, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelAnnouncement { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelAnnouncement>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3370,7 +3532,7 @@ pub struct UnsignedChannelUpdate { impl Drop for UnsignedChannelUpdate { fn drop(&mut self) { if self.is_owned && !<*mut nativeUnsignedChannelUpdate>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3383,11 +3545,17 @@ extern "C" fn UnsignedChannelUpdate_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUnsignedChannelUpdate); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UnsignedChannelUpdate { + pub(crate) fn get_native_ref(&self) -> &'static nativeUnsignedChannelUpdate { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUnsignedChannelUpdate { + 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 nativeUnsignedChannelUpdate { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3395,46 +3563,46 @@ impl UnsignedChannelUpdate { /// The genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_chain_hash(this_ptr: &UnsignedChannelUpdate) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain where the channel is to be opened #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_chain_hash(this_ptr: &mut UnsignedChannelUpdate, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The short channel ID #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_short_channel_id(this_ptr: &UnsignedChannelUpdate) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; *inner_val } /// The short channel ID #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_short_channel_id(this_ptr: &mut UnsignedChannelUpdate, mut val: u64) { - unsafe { &mut *this_ptr.inner }.short_channel_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_timestamp(this_ptr: &UnsignedChannelUpdate) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.timestamp; + let mut inner_val = &mut this_ptr.get_native_mut_ref().timestamp; *inner_val } /// A strictly monotonic announcement counter, with gaps allowed, specific to this channel #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_timestamp(this_ptr: &mut UnsignedChannelUpdate, mut val: u32) { - unsafe { &mut *this_ptr.inner }.timestamp = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp = val; } /// Channel flags #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_flags(this_ptr: &UnsignedChannelUpdate) -> u8 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.flags; + let mut inner_val = &mut this_ptr.get_native_mut_ref().flags; *inner_val } /// Channel flags #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_flags(this_ptr: &mut UnsignedChannelUpdate, mut val: u8) { - unsafe { &mut *this_ptr.inner }.flags = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.flags = val; } /// The number of blocks such that if: /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta` @@ -3446,7 +3614,7 @@ pub extern "C" fn UnsignedChannelUpdate_set_flags(this_ptr: &mut UnsignedChannel /// constructing the route. #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_cltv_expiry_delta(this_ptr: &UnsignedChannelUpdate) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry_delta; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; *inner_val } /// The number of blocks such that if: @@ -3459,46 +3627,46 @@ pub extern "C" fn UnsignedChannelUpdate_get_cltv_expiry_delta(this_ptr: &Unsigne /// constructing the route. #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_cltv_expiry_delta(this_ptr: &mut UnsignedChannelUpdate, mut val: u16) { - unsafe { &mut *this_ptr.inner }.cltv_expiry_delta = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_htlc_minimum_msat(this_ptr: &UnsignedChannelUpdate) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_minimum_msat; *inner_val } /// The minimum HTLC size incoming to sender, in milli-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_htlc_minimum_msat(this_ptr: &mut UnsignedChannelUpdate, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } /// The base HTLC fee charged by sender, in milli-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_fee_base_msat(this_ptr: &UnsignedChannelUpdate) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_base_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_base_msat; *inner_val } /// The base HTLC fee charged by sender, in milli-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_fee_base_msat(this_ptr: &mut UnsignedChannelUpdate, mut val: u32) { - unsafe { &mut *this_ptr.inner }.fee_base_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_base_msat = val; } /// The amount to fee multiplier, in micro-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_fee_proportional_millionths(this_ptr: &UnsignedChannelUpdate) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_proportional_millionths; + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_proportional_millionths; *inner_val } /// The amount to fee multiplier, in micro-satoshi #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_fee_proportional_millionths(this_ptr: &mut UnsignedChannelUpdate, mut val: u32) { - unsafe { &mut *this_ptr.inner }.fee_proportional_millionths = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_proportional_millionths = val; } impl Clone for UnsignedChannelUpdate { fn clone(&self) -> Self { Self { inner: if <*mut nativeUnsignedChannelUpdate>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3536,7 +3704,7 @@ pub struct ChannelUpdate { impl Drop for ChannelUpdate { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelUpdate>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3549,11 +3717,17 @@ extern "C" fn ChannelUpdate_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelUpdate); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelUpdate { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUpdate { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUpdate { + 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 nativeChannelUpdate { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3561,39 +3735,39 @@ impl ChannelUpdate { /// A signature of the channel update #[no_mangle] pub extern "C" fn ChannelUpdate_get_signature(this_ptr: &ChannelUpdate) -> crate::c_types::Signature { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.signature; + let mut inner_val = &mut this_ptr.get_native_mut_ref().signature; crate::c_types::Signature::from_rust(&inner_val) } /// A signature of the channel update #[no_mangle] pub extern "C" fn ChannelUpdate_set_signature(this_ptr: &mut ChannelUpdate, mut val: crate::c_types::Signature) { - unsafe { &mut *this_ptr.inner }.signature = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signature = val.into_rust(); } /// The actual channel update #[no_mangle] pub extern "C" fn ChannelUpdate_get_contents(this_ptr: &ChannelUpdate) -> crate::lightning::ln::msgs::UnsignedChannelUpdate { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.contents; - crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().contents; + crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The actual channel update #[no_mangle] pub extern "C" fn ChannelUpdate_set_contents(this_ptr: &mut ChannelUpdate, mut val: crate::lightning::ln::msgs::UnsignedChannelUpdate) { - unsafe { &mut *this_ptr.inner }.contents = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.contents = *unsafe { Box::from_raw(val.take_inner()) }; } /// Constructs a new ChannelUpdate given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelUpdate_new(mut signature_arg: crate::c_types::Signature, mut contents_arg: crate::lightning::ln::msgs::UnsignedChannelUpdate) -> ChannelUpdate { - ChannelUpdate { inner: Box::into_raw(Box::new(nativeChannelUpdate { + ChannelUpdate { inner: ObjOps::heap_alloc(nativeChannelUpdate { signature: signature_arg.into_rust(), contents: *unsafe { Box::from_raw(contents_arg.take_inner()) }, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelUpdate { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelUpdate>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3634,7 +3808,7 @@ pub struct QueryChannelRange { impl Drop for QueryChannelRange { fn drop(&mut self) { if self.is_owned && !<*mut nativeQueryChannelRange>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3647,11 +3821,17 @@ extern "C" fn QueryChannelRange_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeQueryChannelRange); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl QueryChannelRange { + pub(crate) fn get_native_ref(&self) -> &'static nativeQueryChannelRange { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeQueryChannelRange { + 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 nativeQueryChannelRange { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3659,51 +3839,51 @@ impl QueryChannelRange { /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn QueryChannelRange_get_chain_hash(this_ptr: &QueryChannelRange) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn QueryChannelRange_set_chain_hash(this_ptr: &mut QueryChannelRange, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The height of the first block for the channel UTXOs being queried #[no_mangle] pub extern "C" fn QueryChannelRange_get_first_blocknum(this_ptr: &QueryChannelRange) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.first_blocknum; + let mut inner_val = &mut this_ptr.get_native_mut_ref().first_blocknum; *inner_val } /// The height of the first block for the channel UTXOs being queried #[no_mangle] pub extern "C" fn QueryChannelRange_set_first_blocknum(this_ptr: &mut QueryChannelRange, mut val: u32) { - unsafe { &mut *this_ptr.inner }.first_blocknum = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_blocknum = val; } /// The number of blocks to include in the query results #[no_mangle] pub extern "C" fn QueryChannelRange_get_number_of_blocks(this_ptr: &QueryChannelRange) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.number_of_blocks; + let mut inner_val = &mut this_ptr.get_native_mut_ref().number_of_blocks; *inner_val } /// The number of blocks to include in the query results #[no_mangle] pub extern "C" fn QueryChannelRange_set_number_of_blocks(this_ptr: &mut QueryChannelRange, mut val: u32) { - unsafe { &mut *this_ptr.inner }.number_of_blocks = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.number_of_blocks = val; } /// Constructs a new QueryChannelRange given each field #[must_use] #[no_mangle] pub extern "C" fn QueryChannelRange_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut first_blocknum_arg: u32, mut number_of_blocks_arg: u32) -> QueryChannelRange { - QueryChannelRange { inner: Box::into_raw(Box::new(nativeQueryChannelRange { + QueryChannelRange { inner: ObjOps::heap_alloc(nativeQueryChannelRange { chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(), first_blocknum: first_blocknum_arg, number_of_blocks: number_of_blocks_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for QueryChannelRange { fn clone(&self) -> Self { Self { inner: if <*mut nativeQueryChannelRange>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3747,7 +3927,7 @@ pub struct ReplyChannelRange { impl Drop for ReplyChannelRange { fn drop(&mut self) { if self.is_owned && !<*mut nativeReplyChannelRange>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3760,11 +3940,17 @@ extern "C" fn ReplyChannelRange_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeReplyChannelRange); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ReplyChannelRange { + pub(crate) fn get_native_ref(&self) -> &'static nativeReplyChannelRange { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeReplyChannelRange { + 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 nativeReplyChannelRange { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3772,71 +3958,71 @@ impl ReplyChannelRange { /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn ReplyChannelRange_get_chain_hash(this_ptr: &ReplyChannelRange) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn ReplyChannelRange_set_chain_hash(this_ptr: &mut ReplyChannelRange, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The height of the first block in the range of the reply #[no_mangle] pub extern "C" fn ReplyChannelRange_get_first_blocknum(this_ptr: &ReplyChannelRange) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.first_blocknum; + let mut inner_val = &mut this_ptr.get_native_mut_ref().first_blocknum; *inner_val } /// The height of the first block in the range of the reply #[no_mangle] pub extern "C" fn ReplyChannelRange_set_first_blocknum(this_ptr: &mut ReplyChannelRange, mut val: u32) { - unsafe { &mut *this_ptr.inner }.first_blocknum = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_blocknum = val; } /// The number of blocks included in the range of the reply #[no_mangle] pub extern "C" fn ReplyChannelRange_get_number_of_blocks(this_ptr: &ReplyChannelRange) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.number_of_blocks; + let mut inner_val = &mut this_ptr.get_native_mut_ref().number_of_blocks; *inner_val } /// The number of blocks included in the range of the reply #[no_mangle] pub extern "C" fn ReplyChannelRange_set_number_of_blocks(this_ptr: &mut ReplyChannelRange, mut val: u32) { - unsafe { &mut *this_ptr.inner }.number_of_blocks = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.number_of_blocks = val; } /// True when this is the final reply for a query #[no_mangle] pub extern "C" fn ReplyChannelRange_get_sync_complete(this_ptr: &ReplyChannelRange) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.sync_complete; + let mut inner_val = &mut this_ptr.get_native_mut_ref().sync_complete; *inner_val } /// True when this is the final reply for a query #[no_mangle] pub extern "C" fn ReplyChannelRange_set_sync_complete(this_ptr: &mut ReplyChannelRange, mut val: bool) { - unsafe { &mut *this_ptr.inner }.sync_complete = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.sync_complete = val; } /// The short_channel_ids in the channel range #[no_mangle] pub extern "C" fn ReplyChannelRange_set_short_channel_ids(this_ptr: &mut ReplyChannelRange, mut val: crate::c_types::derived::CVec_u64Z) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; - unsafe { &mut *this_ptr.inner }.short_channel_ids = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_ids = local_val; } /// Constructs a new ReplyChannelRange given each field #[must_use] #[no_mangle] pub extern "C" fn ReplyChannelRange_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut first_blocknum_arg: u32, mut number_of_blocks_arg: u32, mut sync_complete_arg: bool, mut short_channel_ids_arg: crate::c_types::derived::CVec_u64Z) -> ReplyChannelRange { let mut local_short_channel_ids_arg = Vec::new(); for mut item in short_channel_ids_arg.into_rust().drain(..) { local_short_channel_ids_arg.push( { item }); }; - ReplyChannelRange { inner: Box::into_raw(Box::new(nativeReplyChannelRange { + ReplyChannelRange { inner: ObjOps::heap_alloc(nativeReplyChannelRange { chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(), first_blocknum: first_blocknum_arg, number_of_blocks: number_of_blocks_arg, sync_complete: sync_complete_arg, short_channel_ids: local_short_channel_ids_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ReplyChannelRange { fn clone(&self) -> Self { Self { inner: if <*mut nativeReplyChannelRange>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3881,7 +4067,7 @@ pub struct QueryShortChannelIds { impl Drop for QueryShortChannelIds { fn drop(&mut self) { if self.is_owned && !<*mut nativeQueryShortChannelIds>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3894,11 +4080,17 @@ extern "C" fn QueryShortChannelIds_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeQueryShortChannelIds); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl QueryShortChannelIds { + pub(crate) fn get_native_ref(&self) -> &'static nativeQueryShortChannelIds { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeQueryShortChannelIds { + 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 nativeQueryShortChannelIds { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -3906,35 +4098,35 @@ impl QueryShortChannelIds { /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn QueryShortChannelIds_get_chain_hash(this_ptr: &QueryShortChannelIds) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain being queried #[no_mangle] pub extern "C" fn QueryShortChannelIds_set_chain_hash(this_ptr: &mut QueryShortChannelIds, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The short_channel_ids that are being queried #[no_mangle] pub extern "C" fn QueryShortChannelIds_set_short_channel_ids(this_ptr: &mut QueryShortChannelIds, mut val: crate::c_types::derived::CVec_u64Z) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; - unsafe { &mut *this_ptr.inner }.short_channel_ids = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_ids = local_val; } /// Constructs a new QueryShortChannelIds given each field #[must_use] #[no_mangle] pub extern "C" fn QueryShortChannelIds_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut short_channel_ids_arg: crate::c_types::derived::CVec_u64Z) -> QueryShortChannelIds { let mut local_short_channel_ids_arg = Vec::new(); for mut item in short_channel_ids_arg.into_rust().drain(..) { local_short_channel_ids_arg.push( { item }); }; - QueryShortChannelIds { inner: Box::into_raw(Box::new(nativeQueryShortChannelIds { + QueryShortChannelIds { inner: ObjOps::heap_alloc(nativeQueryShortChannelIds { chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(), short_channel_ids: local_short_channel_ids_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for QueryShortChannelIds { fn clone(&self) -> Self { Self { inner: if <*mut nativeQueryShortChannelIds>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -3975,7 +4167,7 @@ pub struct ReplyShortChannelIdsEnd { impl Drop for ReplyShortChannelIdsEnd { fn drop(&mut self) { if self.is_owned && !<*mut nativeReplyShortChannelIdsEnd>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -3988,11 +4180,17 @@ extern "C" fn ReplyShortChannelIdsEnd_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeReplyShortChannelIdsEnd); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ReplyShortChannelIdsEnd { + pub(crate) fn get_native_ref(&self) -> &'static nativeReplyShortChannelIdsEnd { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeReplyShortChannelIdsEnd { + 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 nativeReplyShortChannelIdsEnd { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -4000,41 +4198,41 @@ impl ReplyShortChannelIdsEnd { /// The genesis hash of the blockchain that was queried #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_get_chain_hash(this_ptr: &ReplyShortChannelIdsEnd) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain that was queried #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_set_chain_hash(this_ptr: &mut ReplyShortChannelIdsEnd, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// Indicates if the query recipient maintains up-to-date channel /// information for the chain_hash #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_get_full_information(this_ptr: &ReplyShortChannelIdsEnd) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.full_information; + let mut inner_val = &mut this_ptr.get_native_mut_ref().full_information; *inner_val } /// Indicates if the query recipient maintains up-to-date channel /// information for the chain_hash #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_set_full_information(this_ptr: &mut ReplyShortChannelIdsEnd, mut val: bool) { - unsafe { &mut *this_ptr.inner }.full_information = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.full_information = val; } /// Constructs a new ReplyShortChannelIdsEnd given each field #[must_use] #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut full_information_arg: bool) -> ReplyShortChannelIdsEnd { - ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(nativeReplyShortChannelIdsEnd { + ReplyShortChannelIdsEnd { inner: ObjOps::heap_alloc(nativeReplyShortChannelIdsEnd { chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(), full_information: full_information_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ReplyShortChannelIdsEnd { fn clone(&self) -> Self { Self { inner: if <*mut nativeReplyShortChannelIdsEnd>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -4074,7 +4272,7 @@ pub struct GossipTimestampFilter { impl Drop for GossipTimestampFilter { fn drop(&mut self) { if self.is_owned && !<*mut nativeGossipTimestampFilter>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -4087,11 +4285,17 @@ extern "C" fn GossipTimestampFilter_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeGossipTimestampFilter); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl GossipTimestampFilter { + pub(crate) fn get_native_ref(&self) -> &'static nativeGossipTimestampFilter { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeGossipTimestampFilter { + 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 nativeGossipTimestampFilter { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -4099,51 +4303,51 @@ impl GossipTimestampFilter { /// The genesis hash of the blockchain for channel and node information #[no_mangle] pub extern "C" fn GossipTimestampFilter_get_chain_hash(this_ptr: &GossipTimestampFilter) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_hash; + let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_hash; inner_val.as_inner() } /// The genesis hash of the blockchain for channel and node information #[no_mangle] pub extern "C" fn GossipTimestampFilter_set_chain_hash(this_ptr: &mut GossipTimestampFilter, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// The starting unix timestamp #[no_mangle] pub extern "C" fn GossipTimestampFilter_get_first_timestamp(this_ptr: &GossipTimestampFilter) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.first_timestamp; + let mut inner_val = &mut this_ptr.get_native_mut_ref().first_timestamp; *inner_val } /// The starting unix timestamp #[no_mangle] pub extern "C" fn GossipTimestampFilter_set_first_timestamp(this_ptr: &mut GossipTimestampFilter, mut val: u32) { - unsafe { &mut *this_ptr.inner }.first_timestamp = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_timestamp = val; } /// The range of information in seconds #[no_mangle] pub extern "C" fn GossipTimestampFilter_get_timestamp_range(this_ptr: &GossipTimestampFilter) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.timestamp_range; + let mut inner_val = &mut this_ptr.get_native_mut_ref().timestamp_range; *inner_val } /// The range of information in seconds #[no_mangle] pub extern "C" fn GossipTimestampFilter_set_timestamp_range(this_ptr: &mut GossipTimestampFilter, mut val: u32) { - unsafe { &mut *this_ptr.inner }.timestamp_range = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp_range = val; } /// Constructs a new GossipTimestampFilter given each field #[must_use] #[no_mangle] pub extern "C" fn GossipTimestampFilter_new(mut chain_hash_arg: crate::c_types::ThirtyTwoBytes, mut first_timestamp_arg: u32, mut timestamp_range_arg: u32) -> GossipTimestampFilter { - GossipTimestampFilter { inner: Box::into_raw(Box::new(nativeGossipTimestampFilter { + GossipTimestampFilter { inner: ObjOps::heap_alloc(nativeGossipTimestampFilter { chain_hash: ::bitcoin::hash_types::BlockHash::from_slice(&chain_hash_arg.data[..]).unwrap(), first_timestamp: first_timestamp_arg, timestamp_range: timestamp_range_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for GossipTimestampFilter { fn clone(&self) -> Self { Self { inner: if <*mut nativeGossipTimestampFilter>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -4235,7 +4439,7 @@ impl ErrorAction { match native { nativeErrorAction::DisconnectPeer {ref msg, } => { let mut msg_nonref = (*msg).clone(); - let mut local_msg_nonref = crate::lightning::ln::msgs::ErrorMessage { inner: if msg_nonref.is_none() { std::ptr::null_mut() } else { { Box::into_raw(Box::new((msg_nonref.unwrap()))) } }, is_owned: true }; + let mut local_msg_nonref = crate::lightning::ln::msgs::ErrorMessage { inner: if msg_nonref.is_none() { std::ptr::null_mut() } else { { ObjOps::heap_alloc((msg_nonref.unwrap())) } }, is_owned: true }; ErrorAction::DisconnectPeer { msg: local_msg_nonref, } @@ -4250,7 +4454,7 @@ impl ErrorAction { nativeErrorAction::SendErrorMessage {ref msg, } => { let mut msg_nonref = (*msg).clone(); ErrorAction::SendErrorMessage { - msg: crate::lightning::ln::msgs::ErrorMessage { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ErrorMessage { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, } @@ -4259,7 +4463,7 @@ impl ErrorAction { pub(crate) fn native_into(native: nativeErrorAction) -> Self { match native { nativeErrorAction::DisconnectPeer {mut msg, } => { - let mut local_msg = crate::lightning::ln::msgs::ErrorMessage { inner: if msg.is_none() { std::ptr::null_mut() } else { { Box::into_raw(Box::new((msg.unwrap()))) } }, is_owned: true }; + let mut local_msg = crate::lightning::ln::msgs::ErrorMessage { inner: if msg.is_none() { std::ptr::null_mut() } else { { ObjOps::heap_alloc((msg.unwrap())) } }, is_owned: true }; ErrorAction::DisconnectPeer { msg: local_msg, } @@ -4272,7 +4476,7 @@ impl ErrorAction { }, nativeErrorAction::SendErrorMessage {mut msg, } => { ErrorAction::SendErrorMessage { - msg: crate::lightning::ln::msgs::ErrorMessage { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ErrorMessage { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, } @@ -4332,7 +4536,7 @@ pub struct LightningError { impl Drop for LightningError { fn drop(&mut self) { if self.is_owned && !<*mut nativeLightningError>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -4345,11 +4549,17 @@ extern "C" fn LightningError_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeLightningError); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl LightningError { + pub(crate) fn get_native_ref(&self) -> &'static nativeLightningError { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeLightningError { + 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 nativeLightningError { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -4357,39 +4567,39 @@ impl LightningError { /// A human-readable message describing the error #[no_mangle] pub extern "C" fn LightningError_get_err(this_ptr: &LightningError) -> crate::c_types::Str { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.err; + let mut inner_val = &mut this_ptr.get_native_mut_ref().err; inner_val.as_str().into() } /// A human-readable message describing the error #[no_mangle] pub extern "C" fn LightningError_set_err(this_ptr: &mut LightningError, mut val: crate::c_types::Str) { - unsafe { &mut *this_ptr.inner }.err = val.into_string(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.err = val.into_string(); } /// The action which should be taken against the offending peer. #[no_mangle] pub extern "C" fn LightningError_get_action(this_ptr: &LightningError) -> crate::lightning::ln::msgs::ErrorAction { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.action; + let mut inner_val = &mut this_ptr.get_native_mut_ref().action; crate::lightning::ln::msgs::ErrorAction::from_native(inner_val) } /// The action which should be taken against the offending peer. #[no_mangle] pub extern "C" fn LightningError_set_action(this_ptr: &mut LightningError, mut val: crate::lightning::ln::msgs::ErrorAction) { - unsafe { &mut *this_ptr.inner }.action = val.into_native(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.action = val.into_native(); } /// Constructs a new LightningError given each field #[must_use] #[no_mangle] pub extern "C" fn LightningError_new(mut err_arg: crate::c_types::Str, mut action_arg: crate::lightning::ln::msgs::ErrorAction) -> LightningError { - LightningError { inner: Box::into_raw(Box::new(nativeLightningError { + LightningError { inner: ObjOps::heap_alloc(nativeLightningError { err: err_arg.into_string(), action: action_arg.into_native(), - })), is_owned: true } + }), is_owned: true } } impl Clone for LightningError { fn clone(&self) -> Self { Self { inner: if <*mut nativeLightningError>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -4428,7 +4638,7 @@ pub struct CommitmentUpdate { impl Drop for CommitmentUpdate { fn drop(&mut self) { if self.is_owned && !<*mut nativeCommitmentUpdate>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -4441,11 +4651,17 @@ extern "C" fn CommitmentUpdate_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCommitmentUpdate); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl CommitmentUpdate { + pub(crate) fn get_native_ref(&self) -> &'static nativeCommitmentUpdate { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCommitmentUpdate { + 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 nativeCommitmentUpdate { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -4454,33 +4670,33 @@ impl CommitmentUpdate { #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_add_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateAddHTLCZ) { 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 *this_ptr.inner }.update_add_htlcs = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_add_htlcs = local_val; } /// update_fulfill_htlc messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fulfill_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFulfillHTLCZ) { 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 *this_ptr.inner }.update_fulfill_htlcs = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fulfill_htlcs = local_val; } /// update_fail_htlc messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fail_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailHTLCZ) { 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 *this_ptr.inner }.update_fail_htlcs = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fail_htlcs = local_val; } /// update_fail_malformed_htlc messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fail_malformed_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailMalformedHTLCZ) { 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 *this_ptr.inner }.update_fail_malformed_htlcs = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fail_malformed_htlcs = local_val; } /// An update_fee message which should be sent /// /// 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 CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) -> crate::lightning::ln::msgs::UpdateFee { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_fee; - let mut local_inner_val = crate::lightning::ln::msgs::UpdateFee { 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().update_fee; + let mut local_inner_val = crate::lightning::ln::msgs::UpdateFee { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// An update_fee message which should be sent @@ -4489,18 +4705,18 @@ pub extern "C" fn CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) - #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fee(this_ptr: &mut CommitmentUpdate, mut val: crate::lightning::ln::msgs::UpdateFee) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.update_fee = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fee = local_val; } /// Finally, the commitment_signed message which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_commitment_signed(this_ptr: &CommitmentUpdate) -> crate::lightning::ln::msgs::CommitmentSigned { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commitment_signed; - crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().commitment_signed; + crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Finally, the commitment_signed message which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_commitment_signed(this_ptr: &mut CommitmentUpdate, mut val: crate::lightning::ln::msgs::CommitmentSigned) { - unsafe { &mut *this_ptr.inner }.commitment_signed = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commitment_signed = *unsafe { Box::from_raw(val.take_inner()) }; } /// Constructs a new CommitmentUpdate given each field #[must_use] @@ -4511,20 +4727,20 @@ pub extern "C" fn CommitmentUpdate_new(mut update_add_htlcs_arg: crate::c_types: let mut local_update_fail_htlcs_arg = Vec::new(); for mut item in update_fail_htlcs_arg.into_rust().drain(..) { local_update_fail_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut local_update_fail_malformed_htlcs_arg = Vec::new(); for mut item in update_fail_malformed_htlcs_arg.into_rust().drain(..) { local_update_fail_malformed_htlcs_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut local_update_fee_arg = if update_fee_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(update_fee_arg.take_inner()) } }) }; - CommitmentUpdate { inner: Box::into_raw(Box::new(nativeCommitmentUpdate { + CommitmentUpdate { inner: ObjOps::heap_alloc(nativeCommitmentUpdate { update_add_htlcs: local_update_add_htlcs_arg, update_fulfill_htlcs: local_update_fulfill_htlcs_arg, update_fail_htlcs: local_update_fail_htlcs_arg, update_fail_malformed_htlcs: local_update_fail_malformed_htlcs_arg, update_fee: local_update_fee_arg, commitment_signed: *unsafe { Box::from_raw(commitment_signed_arg.take_inner()) }, - })), is_owned: true } + }), is_owned: true } } impl Clone for CommitmentUpdate { fn clone(&self) -> Self { Self { inner: if <*mut nativeCommitmentUpdate>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -4626,7 +4842,7 @@ impl HTLCFailChannelUpdate { nativeHTLCFailChannelUpdate::ChannelUpdateMessage {ref msg, } => { let mut msg_nonref = (*msg).clone(); HTLCFailChannelUpdate::ChannelUpdateMessage { - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeHTLCFailChannelUpdate::ChannelClosed {ref short_channel_id, ref is_permanent, } => { @@ -4652,7 +4868,7 @@ impl HTLCFailChannelUpdate { match native { nativeHTLCFailChannelUpdate::ChannelUpdateMessage {mut msg, } => { HTLCFailChannelUpdate::ChannelUpdateMessage { - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeHTLCFailChannelUpdate::ChannelClosed {mut short_channel_id, mut is_permanent, } => { @@ -4800,64 +5016,64 @@ impl lightning::util::events::MessageSendEventsProvider for ChannelMessageHandle use lightning::ln::msgs::ChannelMessageHandler as rustChannelMessageHandler; impl rustChannelMessageHandler for ChannelMessageHandler { fn handle_open_channel(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::OpenChannel) { - (self.handle_open_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: Box::into_raw(Box::new(their_features)), is_owned: true }, &crate::lightning::ln::msgs::OpenChannel { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_open_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(their_features), is_owned: true }, &crate::lightning::ln::msgs::OpenChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_accept_channel(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::AcceptChannel) { - (self.handle_accept_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: Box::into_raw(Box::new(their_features)), is_owned: true }, &crate::lightning::ln::msgs::AcceptChannel { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_accept_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(their_features), is_owned: true }, &crate::lightning::ln::msgs::AcceptChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_funding_created(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingCreated) { - (self.handle_funding_created)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingCreated { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_funding_created)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingCreated { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_funding_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingSigned) { - (self.handle_funding_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_funding_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_funding_locked(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::FundingLocked) { - (self.handle_funding_locked)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingLocked { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_funding_locked)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingLocked { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_shutdown(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut their_features: &lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::Shutdown) { - (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::features::InitFeatures { inner: unsafe { (their_features as *const _) as *mut _ }, is_owned: false }, &crate::lightning::ln::msgs::Shutdown { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::features::InitFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((their_features as *const _) as *mut _) }, is_owned: false }, &crate::lightning::ln::msgs::Shutdown { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_closing_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ClosingSigned) { - (self.handle_closing_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ClosingSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_closing_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ClosingSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_update_add_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateAddHTLC) { - (self.handle_update_add_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateAddHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_update_add_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateAddHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_update_fulfill_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFulfillHTLC) { - (self.handle_update_fulfill_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_update_fulfill_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_update_fail_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFailHTLC) { - (self.handle_update_fail_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_update_fail_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_update_fail_malformed_htlc(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFailMalformedHTLC) { - (self.handle_update_fail_malformed_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_update_fail_malformed_htlc)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_commitment_signed(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::CommitmentSigned) { - (self.handle_commitment_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_commitment_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_revoke_and_ack(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::RevokeAndACK) { - (self.handle_revoke_and_ack)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::RevokeAndACK { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_revoke_and_ack)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::RevokeAndACK { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_update_fee(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::UpdateFee) { - (self.handle_update_fee)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFee { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_update_fee)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::UpdateFee { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_announcement_signatures(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::AnnouncementSignatures) { - (self.handle_announcement_signatures)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::AnnouncementSignatures { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_announcement_signatures)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::AnnouncementSignatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut no_connection_possible: bool) { (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), no_connection_possible) } fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::Init) { - (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_channel_reestablish(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ChannelReestablish) { - (self.handle_channel_reestablish)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelReestablish { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_channel_reestablish)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelReestablish { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_channel_update(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ChannelUpdate) { - (self.handle_channel_update)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_channel_update)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } fn handle_error(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: &lightning::ln::msgs::ErrorMessage) { - (self.handle_error)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ErrorMessage { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }) + (self.handle_error)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ErrorMessage { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }) } } @@ -4979,17 +5195,17 @@ impl lightning::util::events::MessageSendEventsProvider for RoutingMessageHandle use lightning::ln::msgs::RoutingMessageHandler as rustRoutingMessageHandler; impl rustRoutingMessageHandler for RoutingMessageHandler { fn handle_node_announcement(&self, mut msg: &lightning::ln::msgs::NodeAnnouncement) -> Result { - let mut ret = (self.handle_node_announcement)(self.this_arg, &crate::lightning::ln::msgs::NodeAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.handle_node_announcement)(self.this_arg, &crate::lightning::ln::msgs::NodeAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }); 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 handle_channel_announcement(&self, mut msg: &lightning::ln::msgs::ChannelAnnouncement) -> Result { - let mut ret = (self.handle_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::ChannelAnnouncement { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.handle_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::ChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }); 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 handle_channel_update(&self, mut msg: &lightning::ln::msgs::ChannelUpdate) -> Result { - let mut ret = (self.handle_channel_update)(self.this_arg, &crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { (msg as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.handle_channel_update)(self.this_arg, &crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const _) as *mut _) }, is_owned: false }); 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 } @@ -5008,25 +5224,25 @@ impl rustRoutingMessageHandler for RoutingMessageHandler { local_ret } fn sync_routing_table(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut init: &lightning::ln::msgs::Init) { - (self.sync_routing_table)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { (init as *const _) as *mut _ }, is_owned: false }) + (self.sync_routing_table)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((init as *const _) as *mut _) }, is_owned: false }) } fn handle_reply_channel_range(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::ReplyChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { - let mut ret = (self.handle_reply_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }); + let mut ret = (self.handle_reply_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyChannelRange { inner: ObjOps::heap_alloc(msg), is_owned: true }); 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 handle_reply_short_channel_ids_end(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::ReplyShortChannelIdsEnd) -> Result<(), lightning::ln::msgs::LightningError> { - let mut ret = (self.handle_reply_short_channel_ids_end)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(msg)), is_owned: true }); + let mut ret = (self.handle_reply_short_channel_ids_end)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: ObjOps::heap_alloc(msg), is_owned: true }); 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 handle_query_channel_range(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::QueryChannelRange) -> Result<(), lightning::ln::msgs::LightningError> { - let mut ret = (self.handle_query_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }); + let mut ret = (self.handle_query_channel_range)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryChannelRange { inner: ObjOps::heap_alloc(msg), is_owned: true }); 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 handle_query_short_channel_ids(&self, mut their_node_id: &bitcoin::secp256k1::key::PublicKey, mut msg: lightning::ln::msgs::QueryShortChannelIds) -> Result<(), lightning::ln::msgs::LightningError> { - let mut ret = (self.handle_query_short_channel_ids)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg)), is_owned: true }); + let mut ret = (self.handle_query_short_channel_ids)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::msgs::QueryShortChannelIds { inner: ObjOps::heap_alloc(msg), is_owned: true }); 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 } @@ -5061,7 +5277,7 @@ use crate::c_types::*; #[no_mangle] /// Serialize the AcceptChannel object into a byte array which can be read by AcceptChannel_read pub extern "C" fn AcceptChannel_write(obj: &AcceptChannel) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn AcceptChannel_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5071,13 +5287,13 @@ pub(crate) extern "C" fn AcceptChannel_write_void(obj: *const c_void) -> crate:: /// Read a AcceptChannel from a byte array, created by AcceptChannel_write pub extern "C" fn AcceptChannel_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_AcceptChannelDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::AcceptChannel { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::AcceptChannel { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the AnnouncementSignatures object into a byte array which can be read by AnnouncementSignatures_read pub extern "C" fn AnnouncementSignatures_write(obj: &AnnouncementSignatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn AnnouncementSignatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5087,13 +5303,13 @@ pub(crate) extern "C" fn AnnouncementSignatures_write_void(obj: *const c_void) - /// Read a AnnouncementSignatures from a byte array, created by AnnouncementSignatures_write pub extern "C" fn AnnouncementSignatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_AnnouncementSignaturesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::AnnouncementSignatures { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::AnnouncementSignatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ChannelReestablish object into a byte array which can be read by ChannelReestablish_read pub extern "C" fn ChannelReestablish_write(obj: &ChannelReestablish) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelReestablish_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5103,13 +5319,13 @@ pub(crate) extern "C" fn ChannelReestablish_write_void(obj: *const c_void) -> cr /// Read a ChannelReestablish from a byte array, created by ChannelReestablish_write pub extern "C" fn ChannelReestablish_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelReestablishDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelReestablish { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelReestablish { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ClosingSigned object into a byte array which can be read by ClosingSigned_read pub extern "C" fn ClosingSigned_write(obj: &ClosingSigned) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ClosingSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5119,13 +5335,13 @@ pub(crate) extern "C" fn ClosingSigned_write_void(obj: *const c_void) -> crate:: /// Read a ClosingSigned from a byte array, created by ClosingSigned_write pub extern "C" fn ClosingSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ClosingSignedDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ClosingSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ClosingSigned { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ClosingSignedFeeRange object into a byte array which can be read by ClosingSignedFeeRange_read pub extern "C" fn ClosingSignedFeeRange_write(obj: &ClosingSignedFeeRange) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ClosingSignedFeeRange_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5135,13 +5351,13 @@ pub(crate) extern "C" fn ClosingSignedFeeRange_write_void(obj: *const c_void) -> /// Read a ClosingSignedFeeRange from a byte array, created by ClosingSignedFeeRange_write pub extern "C" fn ClosingSignedFeeRange_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ClosingSignedFeeRangeDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ClosingSignedFeeRange { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ClosingSignedFeeRange { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the CommitmentSigned object into a byte array which can be read by CommitmentSigned_read pub extern "C" fn CommitmentSigned_write(obj: &CommitmentSigned) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn CommitmentSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5151,13 +5367,13 @@ pub(crate) extern "C" fn CommitmentSigned_write_void(obj: *const c_void) -> crat /// Read a CommitmentSigned from a byte array, created by CommitmentSigned_write pub extern "C" fn CommitmentSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CommitmentSignedDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::CommitmentSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::CommitmentSigned { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the FundingCreated object into a byte array which can be read by FundingCreated_read pub extern "C" fn FundingCreated_write(obj: &FundingCreated) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn FundingCreated_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5167,13 +5383,13 @@ pub(crate) extern "C" fn FundingCreated_write_void(obj: *const c_void) -> crate: /// Read a FundingCreated from a byte array, created by FundingCreated_write pub extern "C" fn FundingCreated_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingCreatedDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingCreated { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingCreated { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the FundingSigned object into a byte array which can be read by FundingSigned_read pub extern "C" fn FundingSigned_write(obj: &FundingSigned) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn FundingSigned_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5183,13 +5399,13 @@ pub(crate) extern "C" fn FundingSigned_write_void(obj: *const c_void) -> crate:: /// Read a FundingSigned from a byte array, created by FundingSigned_write pub extern "C" fn FundingSigned_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingSignedDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingSigned { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingSigned { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the FundingLocked object into a byte array which can be read by FundingLocked_read pub extern "C" fn FundingLocked_write(obj: &FundingLocked) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn FundingLocked_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5199,13 +5415,13 @@ pub(crate) extern "C" fn FundingLocked_write_void(obj: *const c_void) -> crate:: /// Read a FundingLocked from a byte array, created by FundingLocked_write pub extern "C" fn FundingLocked_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FundingLockedDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingLocked { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::FundingLocked { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the Init object into a byte array which can be read by Init_read pub extern "C" fn Init_write(obj: &Init) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn Init_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5215,13 +5431,13 @@ pub(crate) extern "C" fn Init_write_void(obj: *const c_void) -> crate::c_types:: /// Read a Init from a byte array, created by Init_write pub extern "C" fn Init_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InitDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Init { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Init { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the OpenChannel object into a byte array which can be read by OpenChannel_read pub extern "C" fn OpenChannel_write(obj: &OpenChannel) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn OpenChannel_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5231,13 +5447,13 @@ pub(crate) extern "C" fn OpenChannel_write_void(obj: *const c_void) -> crate::c_ /// Read a OpenChannel from a byte array, created by OpenChannel_write pub extern "C" fn OpenChannel_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OpenChannelDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::OpenChannel { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::OpenChannel { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the RevokeAndACK object into a byte array which can be read by RevokeAndACK_read pub extern "C" fn RevokeAndACK_write(obj: &RevokeAndACK) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn RevokeAndACK_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5247,13 +5463,13 @@ pub(crate) extern "C" fn RevokeAndACK_write_void(obj: *const c_void) -> crate::c /// Read a RevokeAndACK from a byte array, created by RevokeAndACK_write pub extern "C" fn RevokeAndACK_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RevokeAndACKDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::RevokeAndACK { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::RevokeAndACK { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the Shutdown object into a byte array which can be read by Shutdown_read pub extern "C" fn Shutdown_write(obj: &Shutdown) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn Shutdown_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5263,13 +5479,13 @@ pub(crate) extern "C" fn Shutdown_write_void(obj: *const c_void) -> crate::c_typ /// Read a Shutdown from a byte array, created by Shutdown_write pub extern "C" fn Shutdown_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ShutdownDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Shutdown { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Shutdown { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UpdateFailHTLC object into a byte array which can be read by UpdateFailHTLC_read pub extern "C" fn UpdateFailHTLC_write(obj: &UpdateFailHTLC) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UpdateFailHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5279,13 +5495,13 @@ pub(crate) extern "C" fn UpdateFailHTLC_write_void(obj: *const c_void) -> crate: /// Read a UpdateFailHTLC from a byte array, created by UpdateFailHTLC_write pub extern "C" fn UpdateFailHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFailHTLCDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFailHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFailHTLC { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UpdateFailMalformedHTLC object into a byte array which can be read by UpdateFailMalformedHTLC_read pub extern "C" fn UpdateFailMalformedHTLC_write(obj: &UpdateFailMalformedHTLC) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UpdateFailMalformedHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5295,13 +5511,13 @@ pub(crate) extern "C" fn UpdateFailMalformedHTLC_write_void(obj: *const c_void) /// Read a UpdateFailMalformedHTLC from a byte array, created by UpdateFailMalformedHTLC_write pub extern "C" fn UpdateFailMalformedHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFailMalformedHTLCDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UpdateFee object into a byte array which can be read by UpdateFee_read pub extern "C" fn UpdateFee_write(obj: &UpdateFee) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UpdateFee_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5311,13 +5527,13 @@ pub(crate) extern "C" fn UpdateFee_write_void(obj: *const c_void) -> crate::c_ty /// Read a UpdateFee from a byte array, created by UpdateFee_write pub extern "C" fn UpdateFee_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFeeDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFee { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFee { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UpdateFulfillHTLC object into a byte array which can be read by UpdateFulfillHTLC_read pub extern "C" fn UpdateFulfillHTLC_write(obj: &UpdateFulfillHTLC) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UpdateFulfillHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5327,13 +5543,13 @@ pub(crate) extern "C" fn UpdateFulfillHTLC_write_void(obj: *const c_void) -> cra /// Read a UpdateFulfillHTLC from a byte array, created by UpdateFulfillHTLC_write pub extern "C" fn UpdateFulfillHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateFulfillHTLCDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UpdateAddHTLC object into a byte array which can be read by UpdateAddHTLC_read pub extern "C" fn UpdateAddHTLC_write(obj: &UpdateAddHTLC) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UpdateAddHTLC_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5343,13 +5559,13 @@ pub(crate) extern "C" fn UpdateAddHTLC_write_void(obj: *const c_void) -> crate:: /// Read a UpdateAddHTLC from a byte array, created by UpdateAddHTLC_write pub extern "C" fn UpdateAddHTLC_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UpdateAddHTLCDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateAddHTLC { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UpdateAddHTLC { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the Ping object into a byte array which can be read by Ping_read pub extern "C" fn Ping_write(obj: &Ping) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn Ping_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5359,13 +5575,13 @@ pub(crate) extern "C" fn Ping_write_void(obj: *const c_void) -> crate::c_types:: /// Read a Ping from a byte array, created by Ping_write pub extern "C" fn Ping_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PingDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Ping { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Ping { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the Pong object into a byte array which can be read by Pong_read pub extern "C" fn Pong_write(obj: &Pong) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn Pong_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5375,13 +5591,13 @@ pub(crate) extern "C" fn Pong_write_void(obj: *const c_void) -> crate::c_types:: /// Read a Pong from a byte array, created by Pong_write pub extern "C" fn Pong_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PongDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Pong { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::Pong { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UnsignedChannelAnnouncement object into a byte array which can be read by UnsignedChannelAnnouncement_read pub extern "C" fn UnsignedChannelAnnouncement_write(obj: &UnsignedChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UnsignedChannelAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5391,13 +5607,13 @@ pub(crate) extern "C" fn UnsignedChannelAnnouncement_write_void(obj: *const c_vo /// Read a UnsignedChannelAnnouncement from a byte array, created by UnsignedChannelAnnouncement_write pub extern "C" fn UnsignedChannelAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedChannelAnnouncementDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ChannelAnnouncement object into a byte array which can be read by ChannelAnnouncement_read pub extern "C" fn ChannelAnnouncement_write(obj: &ChannelAnnouncement) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5407,13 +5623,13 @@ pub(crate) extern "C" fn ChannelAnnouncement_write_void(obj: *const c_void) -> c /// Read a ChannelAnnouncement from a byte array, created by ChannelAnnouncement_write pub extern "C" fn ChannelAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelAnnouncementDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UnsignedChannelUpdate object into a byte array which can be read by UnsignedChannelUpdate_read pub extern "C" fn UnsignedChannelUpdate_write(obj: &UnsignedChannelUpdate) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UnsignedChannelUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5423,13 +5639,13 @@ pub(crate) extern "C" fn UnsignedChannelUpdate_write_void(obj: *const c_void) -> /// Read a UnsignedChannelUpdate from a byte array, created by UnsignedChannelUpdate_write pub extern "C" fn UnsignedChannelUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedChannelUpdateDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ChannelUpdate object into a byte array which can be read by ChannelUpdate_read pub extern "C" fn ChannelUpdate_write(obj: &ChannelUpdate) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5439,13 +5655,13 @@ pub(crate) extern "C" fn ChannelUpdate_write_void(obj: *const c_void) -> crate:: /// Read a ChannelUpdate from a byte array, created by ChannelUpdate_write pub extern "C" fn ChannelUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelUpdateDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ErrorMessage object into a byte array which can be read by ErrorMessage_read pub extern "C" fn ErrorMessage_write(obj: &ErrorMessage) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ErrorMessage_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5455,13 +5671,13 @@ pub(crate) extern "C" fn ErrorMessage_write_void(obj: *const c_void) -> crate::c /// Read a ErrorMessage from a byte array, created by ErrorMessage_write pub extern "C" fn ErrorMessage_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ErrorMessageDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ErrorMessage { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ErrorMessage { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the UnsignedNodeAnnouncement object into a byte array which can be read by UnsignedNodeAnnouncement_read pub extern "C" fn UnsignedNodeAnnouncement_write(obj: &UnsignedNodeAnnouncement) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn UnsignedNodeAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5471,13 +5687,13 @@ pub(crate) extern "C" fn UnsignedNodeAnnouncement_write_void(obj: *const c_void) /// Read a UnsignedNodeAnnouncement from a byte array, created by UnsignedNodeAnnouncement_write pub extern "C" fn UnsignedNodeAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_UnsignedNodeAnnouncementDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the NodeAnnouncement object into a byte array which can be read by NodeAnnouncement_read pub extern "C" fn NodeAnnouncement_write(obj: &NodeAnnouncement) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn NodeAnnouncement_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5487,20 +5703,20 @@ pub(crate) extern "C" fn NodeAnnouncement_write_void(obj: *const c_void) -> crat /// Read a NodeAnnouncement from a byte array, created by NodeAnnouncement_write pub extern "C" fn NodeAnnouncement_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeAnnouncementDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Read a QueryShortChannelIds from a byte array, created by QueryShortChannelIds_write pub extern "C" fn QueryShortChannelIds_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_QueryShortChannelIdsDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::QueryShortChannelIds { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the QueryShortChannelIds object into a byte array which can be read by QueryShortChannelIds_read pub extern "C" fn QueryShortChannelIds_write(obj: &QueryShortChannelIds) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn QueryShortChannelIds_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5510,13 +5726,13 @@ pub(crate) extern "C" fn QueryShortChannelIds_write_void(obj: *const c_void) -> /// Read a ReplyShortChannelIdsEnd from a byte array, created by ReplyShortChannelIdsEnd_write pub extern "C" fn ReplyShortChannelIdsEnd_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ReplyShortChannelIdsEndDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ReplyShortChannelIdsEnd object into a byte array which can be read by ReplyShortChannelIdsEnd_read pub extern "C" fn ReplyShortChannelIdsEnd_write(obj: &ReplyShortChannelIdsEnd) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ReplyShortChannelIdsEnd_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5526,7 +5742,7 @@ pub(crate) extern "C" fn ReplyShortChannelIdsEnd_write_void(obj: *const c_void) #[must_use] #[no_mangle] pub extern "C" fn QueryChannelRange_end_blocknum(this_arg: &QueryChannelRange) -> u32 { - let mut ret = unsafe { &*this_arg.inner }.end_blocknum(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.end_blocknum(); ret } @@ -5534,13 +5750,13 @@ pub extern "C" fn QueryChannelRange_end_blocknum(this_arg: &QueryChannelRange) - /// Read a QueryChannelRange from a byte array, created by QueryChannelRange_write pub extern "C" fn QueryChannelRange_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_QueryChannelRangeDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::QueryChannelRange { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the QueryChannelRange object into a byte array which can be read by QueryChannelRange_read pub extern "C" fn QueryChannelRange_write(obj: &QueryChannelRange) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn QueryChannelRange_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5550,13 +5766,13 @@ pub(crate) extern "C" fn QueryChannelRange_write_void(obj: *const c_void) -> cra /// Read a ReplyChannelRange from a byte array, created by ReplyChannelRange_write pub extern "C" fn ReplyChannelRange_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ReplyChannelRangeDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ReplyChannelRange { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the ReplyChannelRange object into a byte array which can be read by ReplyChannelRange_read pub extern "C" fn ReplyChannelRange_write(obj: &ReplyChannelRange) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ReplyChannelRange_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -5566,13 +5782,13 @@ pub(crate) extern "C" fn ReplyChannelRange_write_void(obj: *const c_void) -> cra /// Read a GossipTimestampFilter from a byte array, created by GossipTimestampFilter_write pub extern "C" fn GossipTimestampFilter_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_GossipTimestampFilterDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::GossipTimestampFilter { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::GossipTimestampFilter { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the GossipTimestampFilter object into a byte array which can be read by GossipTimestampFilter_read pub extern "C" fn GossipTimestampFilter_write(obj: &GossipTimestampFilter) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn GossipTimestampFilter_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { diff --git a/lightning-c-bindings/src/lightning/ln/peer_handler.rs b/lightning-c-bindings/src/lightning/ln/peer_handler.rs index c0a61bc..fda89fc 100644 --- a/lightning-c-bindings/src/lightning/ln/peer_handler.rs +++ b/lightning-c-bindings/src/lightning/ln/peer_handler.rs @@ -43,7 +43,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)) }; } } } @@ -56,11 +56,17 @@ 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -69,12 +75,12 @@ 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(); @@ -87,7 +93,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, } @@ -102,7 +108,7 @@ 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(); @@ -115,7 +121,7 @@ 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, @@ -129,7 +135,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, }, @@ -138,20 +144,20 @@ 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) { @@ -160,41 +166,41 @@ extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_htlc_fail_chan #[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() { std::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() { std::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( { () /*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( { () /*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( { () /*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( { () /*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 } @@ -222,7 +228,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)) }; } } } @@ -235,11 +241,17 @@ 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -249,12 +261,12 @@ 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(); @@ -267,7 +279,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, } @@ -282,7 +294,7 @@ 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(); @@ -295,7 +307,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, @@ -318,7 +330,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, }, @@ -326,64 +338,64 @@ 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()) } @@ -409,7 +421,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)) }; } } } @@ -422,11 +434,17 @@ 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -437,7 +455,7 @@ impl MessageHandler { /// [`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 @@ -446,7 +464,7 @@ pub extern "C" fn MessageHandler_get_chan_handler(this_ptr: &MessageHandler) -> /// [`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 [`NetGraphMsgHandler`] object or an @@ -455,7 +473,7 @@ pub extern "C" fn MessageHandler_set_chan_handler(this_ptr: &mut MessageHandler, /// [`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 @@ -465,16 +483,16 @@ pub extern "C" fn MessageHandler_get_route_handler(this_ptr: &MessageHandler) -> /// [`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 @@ -619,7 +637,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)) }; } } } @@ -632,11 +650,17 @@ 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -645,28 +669,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())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -722,7 +746,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)) }; } } } @@ -735,11 +759,17 @@ 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; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -751,7 +781,7 @@ impl PeerManager { #[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 } + PeerManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Get the list of node ids for peers which have completed the initial handshake. @@ -762,7 +792,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() } @@ -780,8 +810,8 @@ pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &PeerManager) -> crate #[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 } @@ -799,8 +829,8 @@ pub extern "C" fn PeerManager_new_outbound_connection(this_arg: &PeerManager, mu #[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( { () /*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 } @@ -819,8 +849,8 @@ pub extern "C" fn PeerManager_new_inbound_connection(this_arg: &PeerManager, mut #[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( { () /*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 } @@ -841,8 +871,8 @@ pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &PeerManager, d #[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 } @@ -858,13 +888,13 @@ pub extern "C" fn PeerManager_read_event(this_arg: &PeerManager, peer_descriptor /// [`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. #[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. @@ -878,7 +908,7 @@ pub extern "C" fn PeerManager_socket_disconnected(this_arg: &PeerManager, descri /// [`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) } /// Send pings to each peer and disconnect those which did not respond to the last round of @@ -894,6 +924,6 @@ pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &PeerManager, mut /// [`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() } diff --git a/lightning-c-bindings/src/lightning/ln/script.rs b/lightning-c-bindings/src/lightning/ln/script.rs index 7dc4b1d..dcb49dd 100644 --- a/lightning-c-bindings/src/lightning/ln/script.rs +++ b/lightning-c-bindings/src/lightning/ln/script.rs @@ -38,7 +38,7 @@ pub struct ShutdownScript { impl Drop for ShutdownScript { fn drop(&mut self) { if self.is_owned && !<*mut nativeShutdownScript>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -51,11 +51,17 @@ extern "C" fn ShutdownScript_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeShutdownScript); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ShutdownScript { + pub(crate) fn get_native_ref(&self) -> &'static nativeShutdownScript { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeShutdownScript { + 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 nativeShutdownScript { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -64,7 +70,7 @@ impl Clone for ShutdownScript { fn clone(&self) -> Self { Self { inner: if <*mut nativeShutdownScript>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -102,7 +108,7 @@ pub struct InvalidShutdownScript { impl Drop for InvalidShutdownScript { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvalidShutdownScript>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -115,11 +121,17 @@ extern "C" fn InvalidShutdownScript_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvalidShutdownScript); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InvalidShutdownScript { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvalidShutdownScript { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvalidShutdownScript { + 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 nativeInvalidShutdownScript { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -129,7 +141,7 @@ impl InvalidShutdownScript { /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md #[no_mangle] pub extern "C" fn InvalidShutdownScript_get_script(this_ptr: &InvalidShutdownScript) -> crate::c_types::u8slice { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.script; + let mut inner_val = &mut this_ptr.get_native_mut_ref().script; crate::c_types::u8slice::from_slice(&inner_val[..]) } /// The script that did not meet the requirements from [BOLT #2]. @@ -137,20 +149,20 @@ pub extern "C" fn InvalidShutdownScript_get_script(this_ptr: &InvalidShutdownScr /// [BOLT #2]: https://github.com/lightningnetwork/lightning-rfc/blob/master/02-peer-protocol.md #[no_mangle] pub extern "C" fn InvalidShutdownScript_set_script(this_ptr: &mut InvalidShutdownScript, mut val: crate::c_types::derived::CVec_u8Z) { - unsafe { &mut *this_ptr.inner }.script = ::bitcoin::blockdata::script::Script::from(val.into_rust()); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.script = ::bitcoin::blockdata::script::Script::from(val.into_rust()); } /// Constructs a new InvalidShutdownScript given each field #[must_use] #[no_mangle] pub extern "C" fn InvalidShutdownScript_new(mut script_arg: crate::c_types::derived::CVec_u8Z) -> InvalidShutdownScript { - InvalidShutdownScript { inner: Box::into_raw(Box::new(nativeInvalidShutdownScript { + InvalidShutdownScript { inner: ObjOps::heap_alloc(nativeInvalidShutdownScript { script: ::bitcoin::blockdata::script::Script::from(script_arg.into_rust()), - })), is_owned: true } + }), is_owned: true } } #[no_mangle] /// Serialize the ShutdownScript object into a byte array which can be read by ShutdownScript_read pub extern "C" fn ShutdownScript_write(obj: &ShutdownScript) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ShutdownScript_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -160,7 +172,7 @@ pub(crate) extern "C" fn ShutdownScript_write_void(obj: *const c_void) -> crate: /// Read a ShutdownScript from a byte array, created by ShutdownScript_write pub extern "C" fn ShutdownScript_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ShutdownScriptDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Generates a P2PKH script pubkey from the given [`PubkeyHash`]. @@ -168,7 +180,7 @@ pub extern "C" fn ShutdownScript_read(ser: crate::c_types::u8slice) -> crate::c_ #[no_mangle] pub extern "C" fn ShutdownScript_new_p2pkh(pubkey_hash: *const [u8; 20]) -> ShutdownScript { let mut ret = lightning::ln::script::ShutdownScript::new_p2pkh(&bitcoin::hash_types::PubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *pubkey_hash }.clone()))); - ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Generates a P2SH script pubkey from the given [`ScriptHash`]. @@ -176,7 +188,7 @@ pub extern "C" fn ShutdownScript_new_p2pkh(pubkey_hash: *const [u8; 20]) -> Shut #[no_mangle] pub extern "C" fn ShutdownScript_new_p2sh(script_hash: *const [u8; 20]) -> ShutdownScript { let mut ret = lightning::ln::script::ShutdownScript::new_p2sh(&bitcoin::hash_types::ScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *script_hash }.clone()))); - ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Generates a P2WPKH script pubkey from the given [`WPubkeyHash`]. @@ -184,7 +196,7 @@ pub extern "C" fn ShutdownScript_new_p2sh(script_hash: *const [u8; 20]) -> Shutd #[no_mangle] pub extern "C" fn ShutdownScript_new_p2wpkh(pubkey_hash: *const [u8; 20]) -> ShutdownScript { let mut ret = lightning::ln::script::ShutdownScript::new_p2wpkh(&bitcoin::hash_types::WPubkeyHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *pubkey_hash }.clone()))); - ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Generates a P2WSH script pubkey from the given [`WScriptHash`]. @@ -192,7 +204,7 @@ pub extern "C" fn ShutdownScript_new_p2wpkh(pubkey_hash: *const [u8; 20]) -> Shu #[no_mangle] pub extern "C" fn ShutdownScript_new_p2wsh(script_hash: *const [u8; 32]) -> ShutdownScript { let mut ret = lightning::ln::script::ShutdownScript::new_p2wsh(&bitcoin::hash_types::WScriptHash::from_hash(bitcoin::hashes::Hash::from_inner(unsafe { *script_hash }.clone()))); - ShutdownScript { inner: Box::into_raw(Box::new(ret)), is_owned: true } + ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Generates a P2WSH script pubkey from the given segwit version and program. @@ -204,7 +216,7 @@ pub extern "C" fn ShutdownScript_new_p2wsh(script_hash: *const [u8; 32]) -> Shut #[no_mangle] pub extern "C" fn ShutdownScript_new_witness_program(mut version: u8, mut program: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ShutdownScriptInvalidShutdownScriptZ { let mut ret = lightning::ln::script::ShutdownScript::new_witness_program(core::num::NonZeroU8::new(version).expect("Value must be non-zero"), program.to_slice()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::script::InvalidShutdownScript { 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( { crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::script::InvalidShutdownScript { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -222,7 +234,7 @@ pub extern "C" fn ShutdownScript_into_inner(mut this_arg: ShutdownScript) -> cra #[must_use] #[no_mangle] pub extern "C" fn ShutdownScript_as_legacy_pubkey(this_arg: &ShutdownScript) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.as_legacy_pubkey(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_legacy_pubkey(); let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } }; local_ret } @@ -233,7 +245,7 @@ pub extern "C" fn ShutdownScript_as_legacy_pubkey(this_arg: &ShutdownScript) -> #[must_use] #[no_mangle] pub extern "C" fn ShutdownScript_is_compatible(this_arg: &ShutdownScript, features: &crate::lightning::ln::features::InitFeatures) -> bool { - let mut ret = unsafe { &*this_arg.inner }.is_compatible(unsafe { &*features.inner }); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.is_compatible(features.get_native_ref()); ret } diff --git a/lightning-c-bindings/src/lightning/routing/network_graph.rs b/lightning-c-bindings/src/lightning/routing/network_graph.rs index 894d052..fe64794 100644 --- a/lightning-c-bindings/src/lightning/routing/network_graph.rs +++ b/lightning-c-bindings/src/lightning/routing/network_graph.rs @@ -36,7 +36,7 @@ pub struct NetworkGraph { impl Drop for NetworkGraph { fn drop(&mut self) { if self.is_owned && !<*mut nativeNetworkGraph>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -49,11 +49,17 @@ extern "C" fn NetworkGraph_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNetworkGraph); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NetworkGraph { + pub(crate) fn get_native_ref(&self) -> &'static nativeNetworkGraph { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNetworkGraph { + 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 nativeNetworkGraph { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -62,7 +68,7 @@ impl Clone for NetworkGraph { fn clone(&self) -> Self { Self { inner: if <*mut nativeNetworkGraph>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -102,7 +108,7 @@ pub struct LockedNetworkGraph { impl Drop for LockedNetworkGraph { fn drop(&mut self) { if self.is_owned && !<*mut nativeLockedNetworkGraph>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -115,11 +121,17 @@ extern "C" fn LockedNetworkGraph_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeLockedNetworkGraph); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl LockedNetworkGraph { + pub(crate) fn get_native_ref(&self) -> &'static nativeLockedNetworkGraph { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeLockedNetworkGraph { + 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 nativeLockedNetworkGraph { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -151,7 +163,7 @@ pub struct NetGraphMsgHandler { impl Drop for NetGraphMsgHandler { fn drop(&mut self) { if self.is_owned && !<*mut nativeNetGraphMsgHandler>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -164,11 +176,17 @@ extern "C" fn NetGraphMsgHandler_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNetGraphMsgHandler); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NetGraphMsgHandler { + pub(crate) fn get_native_ref(&self) -> &'static nativeNetGraphMsgHandler { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNetGraphMsgHandler { + 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 nativeNetGraphMsgHandler { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -185,7 +203,7 @@ impl NetGraphMsgHandler { pub extern "C" fn NetGraphMsgHandler_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes, chain_access: *mut crate::lightning::chain::Access, mut logger: crate::lightning::util::logger::Logger) -> NetGraphMsgHandler { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::new(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap(), local_chain_access, logger); - NetGraphMsgHandler { inner: Box::into_raw(Box::new(ret)), is_owned: true } + NetGraphMsgHandler { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a new tracker of the actual state of the network of channels and nodes, @@ -197,7 +215,7 @@ pub extern "C" fn NetGraphMsgHandler_new(mut genesis_hash: crate::c_types::Thirt pub extern "C" fn NetGraphMsgHandler_from_net_graph(chain_access: *mut crate::lightning::chain::Access, mut logger: crate::lightning::util::logger::Logger, mut network_graph: crate::lightning::routing::network_graph::NetworkGraph) -> NetGraphMsgHandler { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; let mut ret = lightning::routing::network_graph::NetGraphMsgHandler::from_net_graph(local_chain_access, logger, *unsafe { Box::from_raw(network_graph.take_inner()) }); - NetGraphMsgHandler { inner: Box::into_raw(Box::new(ret)), is_owned: true } + NetGraphMsgHandler { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Adds a provider used to check new announcements. Does not affect @@ -208,7 +226,7 @@ pub extern "C" fn NetGraphMsgHandler_from_net_graph(chain_access: *mut crate::li #[no_mangle] pub extern "C" fn NetGraphMsgHandler_add_chain_access(this_arg: &mut NetGraphMsgHandler, chain_access: *mut crate::lightning::chain::Access) { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; - unsafe { &mut (*(this_arg.inner as *mut nativeNetGraphMsgHandler)) }.add_chain_access(local_chain_access) + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetGraphMsgHandler)) }.add_chain_access(local_chain_access) } /// Take a read lock on the network_graph and return it in the C-bindings @@ -218,21 +236,21 @@ pub extern "C" fn NetGraphMsgHandler_add_chain_access(this_arg: &mut NetGraphMsg #[must_use] #[no_mangle] pub extern "C" fn NetGraphMsgHandler_read_locked_graph(this_arg: &NetGraphMsgHandler) -> crate::lightning::routing::network_graph::LockedNetworkGraph { - let mut ret = unsafe { &*this_arg.inner }.read_locked_graph(); - crate::lightning::routing::network_graph::LockedNetworkGraph { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_locked_graph(); + crate::lightning::routing::network_graph::LockedNetworkGraph { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Get a reference to the NetworkGraph which this read-lock contains. #[must_use] #[no_mangle] pub extern "C" fn LockedNetworkGraph_graph(this_arg: &LockedNetworkGraph) -> crate::lightning::routing::network_graph::NetworkGraph { - let mut ret = unsafe { &*this_arg.inner }.graph(); - crate::lightning::routing::network_graph::NetworkGraph { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.graph(); + crate::lightning::routing::network_graph::NetworkGraph { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } impl From for crate::lightning::ln::msgs::RoutingMessageHandler { fn from(obj: nativeNetGraphMsgHandler) -> Self { - let mut rust_obj = NetGraphMsgHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = NetGraphMsgHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = NetGraphMsgHandler_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(); @@ -245,7 +263,7 @@ impl From for crate::lightning::ln::msgs::RoutingMessa #[no_mangle] pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: &NetGraphMsgHandler) -> 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: NetGraphMsgHandler_RoutingMessageHandler_handle_node_announcement, handle_channel_announcement: NetGraphMsgHandler_RoutingMessageHandler_handle_channel_announcement, @@ -259,7 +277,7 @@ pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: &NetGrap handle_query_channel_range: NetGraphMsgHandler_RoutingMessageHandler_handle_query_channel_range, handle_query_short_channel_ids: NetGraphMsgHandler_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: NetGraphMsgHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, }, @@ -268,14 +286,14 @@ pub extern "C" fn NetGraphMsgHandler_as_RoutingMessageHandler(this_arg: &NetGrap #[must_use] extern "C" fn NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, 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 nativeNetGraphMsgHandler) }, 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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, 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 nativeNetGraphMsgHandler) }, 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 NetGraphMsgHandler_RoutingMessageHandler_handle_htlc_fail_channel_update(this_arg: *const c_void, update: &crate::lightning::ln::msgs::HTLCFailChannelUpdate) { @@ -283,54 +301,54 @@ extern "C" fn NetGraphMsgHandler_RoutingMessageHandler_handle_htlc_fail_channel_ } #[must_use] extern "C" fn NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, 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 nativeNetGraphMsgHandler) }, 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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, 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() { std::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() { std::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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, 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 NetGraphMsgHandler_RoutingMessageHandler_sync_routing_table(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init_msg: &crate::lightning::ln::msgs::Init) { - >::sync_routing_table(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), unsafe { &*init_msg.inner }) + >::sync_routing_table(unsafe { &mut *(this_arg as *mut nativeNetGraphMsgHandler) }, &their_node_id.into_rust(), init_msg.get_native_ref()) } #[must_use] extern "C" fn NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, &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( { () /*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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, &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( { () /*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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, &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( { () /*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 NetGraphMsgHandler_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 nativeNetGraphMsgHandler) }, &_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( { () /*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 } impl From for crate::lightning::util::events::MessageSendEventsProvider { fn from(obj: nativeNetGraphMsgHandler) -> Self { - let mut rust_obj = NetGraphMsgHandler { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = NetGraphMsgHandler { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = NetGraphMsgHandler_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(); @@ -343,7 +361,7 @@ impl From for crate::lightning::util::events::MessageS #[no_mangle] pub extern "C" fn NetGraphMsgHandler_as_MessageSendEventsProvider(this_arg: &NetGraphMsgHandler) -> 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: NetGraphMsgHandler_MessageSendEventsProvider_get_and_clear_pending_msg_events, } @@ -380,7 +398,7 @@ pub struct DirectionalChannelInfo { impl Drop for DirectionalChannelInfo { fn drop(&mut self) { if self.is_owned && !<*mut nativeDirectionalChannelInfo>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -393,11 +411,17 @@ extern "C" fn DirectionalChannelInfo_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDirectionalChannelInfo); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl DirectionalChannelInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativeDirectionalChannelInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDirectionalChannelInfo { + 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 nativeDirectionalChannelInfo { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -406,52 +430,52 @@ impl DirectionalChannelInfo { /// Value is opaque, as set in the announcement. #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_last_update(this_ptr: &DirectionalChannelInfo) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.last_update; + let mut inner_val = &mut this_ptr.get_native_mut_ref().last_update; *inner_val } /// When the last update to the channel direction was issued. /// Value is opaque, as set in the announcement. #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_last_update(this_ptr: &mut DirectionalChannelInfo, mut val: u32) { - unsafe { &mut *this_ptr.inner }.last_update = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.last_update = val; } /// Whether the channel can be currently used for payments (in this one direction). #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_enabled(this_ptr: &DirectionalChannelInfo) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.enabled; + let mut inner_val = &mut this_ptr.get_native_mut_ref().enabled; *inner_val } /// Whether the channel can be currently used for payments (in this one direction). #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_enabled(this_ptr: &mut DirectionalChannelInfo, mut val: bool) { - unsafe { &mut *this_ptr.inner }.enabled = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.enabled = val; } /// The difference in CLTV values that you must have when routing through this channel. #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_cltv_expiry_delta(this_ptr: &DirectionalChannelInfo) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry_delta; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; *inner_val } /// The difference in CLTV values that you must have when routing through this channel. #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_cltv_expiry_delta(this_ptr: &mut DirectionalChannelInfo, mut val: u16) { - unsafe { &mut *this_ptr.inner }.cltv_expiry_delta = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; } /// The minimum value, which must be relayed to the next hop via the channel #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_htlc_minimum_msat(this_ptr: &DirectionalChannelInfo) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_minimum_msat; *inner_val } /// The minimum value, which must be relayed to the next hop via the channel #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_htlc_minimum_msat(this_ptr: &mut DirectionalChannelInfo, mut val: u64) { - unsafe { &mut *this_ptr.inner }.htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } /// The maximum value which may be relayed to the next hop via the channel. #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_htlc_maximum_msat(this_ptr: &DirectionalChannelInfo) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_maximum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().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 } @@ -459,18 +483,18 @@ pub extern "C" fn DirectionalChannelInfo_get_htlc_maximum_msat(this_ptr: &Direct #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_htlc_maximum_msat(this_ptr: &mut DirectionalChannelInfo, 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 }.htlc_maximum_msat = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_maximum_msat = local_val; } /// Fees charged when the channel is used for routing #[no_mangle] pub extern "C" fn DirectionalChannelInfo_get_fees(this_ptr: &DirectionalChannelInfo) -> crate::lightning::routing::network_graph::RoutingFees { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fees; - crate::lightning::routing::network_graph::RoutingFees { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().fees; + crate::lightning::routing::network_graph::RoutingFees { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Fees charged when the channel is used for routing #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_fees(this_ptr: &mut DirectionalChannelInfo, mut val: crate::lightning::routing::network_graph::RoutingFees) { - unsafe { &mut *this_ptr.inner }.fees = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fees = *unsafe { Box::from_raw(val.take_inner()) }; } /// Most recent update for the channel received from the network /// Mostly redundant with the data we store in fields explicitly. @@ -480,8 +504,8 @@ pub extern "C" fn DirectionalChannelInfo_set_fees(this_ptr: &mut DirectionalChan /// 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 DirectionalChannelInfo_get_last_update_message(this_ptr: &DirectionalChannelInfo) -> crate::lightning::ln::msgs::ChannelUpdate { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.last_update_message; - let mut local_inner_val = crate::lightning::ln::msgs::ChannelUpdate { 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().last_update_message; + let mut local_inner_val = crate::lightning::ln::msgs::ChannelUpdate { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// Most recent update for the channel received from the network @@ -493,7 +517,7 @@ pub extern "C" fn DirectionalChannelInfo_get_last_update_message(this_ptr: &Dire #[no_mangle] pub extern "C" fn DirectionalChannelInfo_set_last_update_message(this_ptr: &mut DirectionalChannelInfo, mut val: crate::lightning::ln::msgs::ChannelUpdate) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.last_update_message = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.last_update_message = local_val; } /// Constructs a new DirectionalChannelInfo given each field #[must_use] @@ -501,7 +525,7 @@ pub extern "C" fn DirectionalChannelInfo_set_last_update_message(this_ptr: &mut pub extern "C" fn DirectionalChannelInfo_new(mut last_update_arg: u32, mut enabled_arg: bool, mut cltv_expiry_delta_arg: u16, mut htlc_minimum_msat_arg: u64, mut htlc_maximum_msat_arg: crate::c_types::derived::COption_u64Z, mut fees_arg: crate::lightning::routing::network_graph::RoutingFees, mut last_update_message_arg: crate::lightning::ln::msgs::ChannelUpdate) -> DirectionalChannelInfo { let mut local_htlc_maximum_msat_arg = if htlc_maximum_msat_arg.is_some() { Some( { htlc_maximum_msat_arg.take() }) } else { None }; let mut local_last_update_message_arg = if last_update_message_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(last_update_message_arg.take_inner()) } }) }; - DirectionalChannelInfo { inner: Box::into_raw(Box::new(nativeDirectionalChannelInfo { + DirectionalChannelInfo { inner: ObjOps::heap_alloc(nativeDirectionalChannelInfo { last_update: last_update_arg, enabled: enabled_arg, cltv_expiry_delta: cltv_expiry_delta_arg, @@ -509,13 +533,13 @@ pub extern "C" fn DirectionalChannelInfo_new(mut last_update_arg: u32, mut enabl htlc_maximum_msat: local_htlc_maximum_msat_arg, fees: *unsafe { Box::from_raw(fees_arg.take_inner()) }, last_update_message: local_last_update_message_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for DirectionalChannelInfo { fn clone(&self) -> Self { Self { inner: if <*mut nativeDirectionalChannelInfo>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -533,7 +557,7 @@ pub extern "C" fn DirectionalChannelInfo_clone(orig: &DirectionalChannelInfo) -> #[no_mangle] /// Serialize the DirectionalChannelInfo object into a byte array which can be read by DirectionalChannelInfo_read pub extern "C" fn DirectionalChannelInfo_write(obj: &DirectionalChannelInfo) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn DirectionalChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -543,7 +567,7 @@ pub(crate) extern "C" fn DirectionalChannelInfo_write_void(obj: *const c_void) - /// Read a DirectionalChannelInfo from a byte array, created by DirectionalChannelInfo_write pub extern "C" fn DirectionalChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_DirectionalChannelInfoDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::DirectionalChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::DirectionalChannelInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -570,7 +594,7 @@ pub struct ChannelInfo { impl Drop for ChannelInfo { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelInfo>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -583,11 +607,17 @@ extern "C" fn ChannelInfo_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelInfo); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelInfo { + 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 nativeChannelInfo { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -595,32 +625,32 @@ impl ChannelInfo { /// Protocol features of a channel communicated during its announcement #[no_mangle] pub extern "C" fn ChannelInfo_get_features(this_ptr: &ChannelInfo) -> crate::lightning::ln::features::ChannelFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features; - crate::lightning::ln::features::ChannelFeatures { 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::ChannelFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Protocol features of a channel communicated during its announcement #[no_mangle] pub extern "C" fn ChannelInfo_set_features(this_ptr: &mut ChannelInfo, mut val: crate::lightning::ln::features::ChannelFeatures) { - 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()) }; } /// Source node of the first direction of a channel #[no_mangle] pub extern "C" fn ChannelInfo_get_node_one(this_ptr: &ChannelInfo) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_one; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_one; crate::c_types::PublicKey::from_rust(&inner_val) } /// Source node of the first direction of a channel #[no_mangle] pub extern "C" fn ChannelInfo_set_node_one(this_ptr: &mut ChannelInfo, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.node_one = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_one = val.into_rust(); } /// Details about the first direction of a 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 ChannelInfo_get_one_to_two(this_ptr: &ChannelInfo) -> crate::lightning::routing::network_graph::DirectionalChannelInfo { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.one_to_two; - let mut local_inner_val = crate::lightning::routing::network_graph::DirectionalChannelInfo { 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().one_to_two; + let mut local_inner_val = crate::lightning::routing::network_graph::DirectionalChannelInfo { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// Details about the first direction of a channel @@ -629,26 +659,26 @@ pub extern "C" fn ChannelInfo_get_one_to_two(this_ptr: &ChannelInfo) -> crate::l #[no_mangle] pub extern "C" fn ChannelInfo_set_one_to_two(this_ptr: &mut ChannelInfo, mut val: crate::lightning::routing::network_graph::DirectionalChannelInfo) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.one_to_two = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.one_to_two = local_val; } /// Source node of the second direction of a channel #[no_mangle] pub extern "C" fn ChannelInfo_get_node_two(this_ptr: &ChannelInfo) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_two; + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_two; crate::c_types::PublicKey::from_rust(&inner_val) } /// Source node of the second direction of a channel #[no_mangle] pub extern "C" fn ChannelInfo_set_node_two(this_ptr: &mut ChannelInfo, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.node_two = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_two = val.into_rust(); } /// Details about the second direction of a 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 ChannelInfo_get_two_to_one(this_ptr: &ChannelInfo) -> crate::lightning::routing::network_graph::DirectionalChannelInfo { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.two_to_one; - let mut local_inner_val = crate::lightning::routing::network_graph::DirectionalChannelInfo { 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().two_to_one; + let mut local_inner_val = crate::lightning::routing::network_graph::DirectionalChannelInfo { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// Details about the second direction of a channel @@ -657,12 +687,12 @@ pub extern "C" fn ChannelInfo_get_two_to_one(this_ptr: &ChannelInfo) -> crate::l #[no_mangle] pub extern "C" fn ChannelInfo_set_two_to_one(this_ptr: &mut ChannelInfo, mut val: crate::lightning::routing::network_graph::DirectionalChannelInfo) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.two_to_one = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.two_to_one = local_val; } /// The channel capacity as seen on-chain, if chain lookup is available. #[no_mangle] pub extern "C" fn ChannelInfo_get_capacity_sats(this_ptr: &ChannelInfo) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.capacity_sats; + let mut inner_val = &mut this_ptr.get_native_mut_ref().capacity_sats; 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 } @@ -670,7 +700,7 @@ pub extern "C" fn ChannelInfo_get_capacity_sats(this_ptr: &ChannelInfo) -> crate #[no_mangle] pub extern "C" fn ChannelInfo_set_capacity_sats(this_ptr: &mut ChannelInfo, 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 }.capacity_sats = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.capacity_sats = local_val; } /// An initial announcement of the channel /// Mostly redundant with the data we store in fields explicitly. @@ -680,8 +710,8 @@ pub extern "C" fn ChannelInfo_set_capacity_sats(this_ptr: &mut ChannelInfo, mut /// 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 ChannelInfo_get_announcement_message(this_ptr: &ChannelInfo) -> crate::lightning::ln::msgs::ChannelAnnouncement { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_message; - let mut local_inner_val = crate::lightning::ln::msgs::ChannelAnnouncement { 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().announcement_message; + let mut local_inner_val = crate::lightning::ln::msgs::ChannelAnnouncement { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// An initial announcement of the channel @@ -693,7 +723,7 @@ pub extern "C" fn ChannelInfo_get_announcement_message(this_ptr: &ChannelInfo) - #[no_mangle] pub extern "C" fn ChannelInfo_set_announcement_message(this_ptr: &mut ChannelInfo, mut val: crate::lightning::ln::msgs::ChannelAnnouncement) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.announcement_message = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.announcement_message = local_val; } /// Constructs a new ChannelInfo given each field #[must_use] @@ -703,7 +733,7 @@ pub extern "C" fn ChannelInfo_new(mut features_arg: crate::lightning::ln::featur let mut local_two_to_one_arg = if two_to_one_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(two_to_one_arg.take_inner()) } }) }; let mut local_capacity_sats_arg = if capacity_sats_arg.is_some() { Some( { capacity_sats_arg.take() }) } else { None }; let mut local_announcement_message_arg = if announcement_message_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_message_arg.take_inner()) } }) }; - ChannelInfo { inner: Box::into_raw(Box::new(nativeChannelInfo { + ChannelInfo { inner: ObjOps::heap_alloc(nativeChannelInfo { features: *unsafe { Box::from_raw(features_arg.take_inner()) }, node_one: node_one_arg.into_rust(), one_to_two: local_one_to_two_arg, @@ -711,13 +741,13 @@ pub extern "C" fn ChannelInfo_new(mut features_arg: crate::lightning::ln::featur two_to_one: local_two_to_one_arg, capacity_sats: local_capacity_sats_arg, announcement_message: local_announcement_message_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelInfo { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelInfo>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -735,7 +765,7 @@ pub extern "C" fn ChannelInfo_clone(orig: &ChannelInfo) -> ChannelInfo { #[no_mangle] /// Serialize the ChannelInfo object into a byte array which can be read by ChannelInfo_read pub extern "C" fn ChannelInfo_write(obj: &ChannelInfo) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -745,7 +775,7 @@ pub(crate) extern "C" fn ChannelInfo_write_void(obj: *const c_void) -> crate::c_ /// Read a ChannelInfo from a byte array, created by ChannelInfo_write pub extern "C" fn ChannelInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelInfoDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::ChannelInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::ChannelInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -771,7 +801,7 @@ pub struct RoutingFees { impl Drop for RoutingFees { fn drop(&mut self) { if self.is_owned && !<*mut nativeRoutingFees>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -784,11 +814,17 @@ extern "C" fn RoutingFees_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRoutingFees); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RoutingFees { + pub(crate) fn get_native_ref(&self) -> &'static nativeRoutingFees { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRoutingFees { + 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 nativeRoutingFees { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -796,35 +832,35 @@ impl RoutingFees { /// Flat routing fee in satoshis #[no_mangle] pub extern "C" fn RoutingFees_get_base_msat(this_ptr: &RoutingFees) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.base_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().base_msat; *inner_val } /// Flat routing fee in satoshis #[no_mangle] pub extern "C" fn RoutingFees_set_base_msat(this_ptr: &mut RoutingFees, mut val: u32) { - unsafe { &mut *this_ptr.inner }.base_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_msat = val; } /// Liquidity-based routing fee in millionths of a routed amount. /// In other words, 10000 is 1%. #[no_mangle] pub extern "C" fn RoutingFees_get_proportional_millionths(this_ptr: &RoutingFees) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.proportional_millionths; + let mut inner_val = &mut this_ptr.get_native_mut_ref().proportional_millionths; *inner_val } /// Liquidity-based routing fee in millionths of a routed amount. /// In other words, 10000 is 1%. #[no_mangle] pub extern "C" fn RoutingFees_set_proportional_millionths(this_ptr: &mut RoutingFees, mut val: u32) { - unsafe { &mut *this_ptr.inner }.proportional_millionths = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.proportional_millionths = val; } /// Constructs a new RoutingFees given each field #[must_use] #[no_mangle] pub extern "C" fn RoutingFees_new(mut base_msat_arg: u32, mut proportional_millionths_arg: u32) -> RoutingFees { - RoutingFees { inner: Box::into_raw(Box::new(nativeRoutingFees { + RoutingFees { inner: ObjOps::heap_alloc(nativeRoutingFees { base_msat: base_msat_arg, proportional_millionths: proportional_millionths_arg, - })), is_owned: true } + }), is_owned: true } } /// Checks if two RoutingFeess contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -833,13 +869,13 @@ pub extern "C" fn RoutingFees_new(mut base_msat_arg: u32, mut proportional_milli pub extern "C" fn RoutingFees_eq(a: &RoutingFees, b: &RoutingFees) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RoutingFees { fn clone(&self) -> Self { Self { inner: if <*mut nativeRoutingFees>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -857,7 +893,7 @@ pub extern "C" fn RoutingFees_clone(orig: &RoutingFees) -> RoutingFees { #[no_mangle] /// Serialize the RoutingFees object into a byte array which can be read by RoutingFees_read pub extern "C" fn RoutingFees_write(obj: &RoutingFees) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn RoutingFees_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -867,7 +903,7 @@ pub(crate) extern "C" fn RoutingFees_write_void(obj: *const c_void) -> crate::c_ /// Read a RoutingFees from a byte array, created by RoutingFees_write pub extern "C" fn RoutingFees_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RoutingFeesDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::RoutingFees { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::RoutingFees { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -893,7 +929,7 @@ pub struct NodeAnnouncementInfo { impl Drop for NodeAnnouncementInfo { fn drop(&mut self) { if self.is_owned && !<*mut nativeNodeAnnouncementInfo>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -906,11 +942,17 @@ extern "C" fn NodeAnnouncementInfo_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNodeAnnouncementInfo); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NodeAnnouncementInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativeNodeAnnouncementInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNodeAnnouncementInfo { + 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 nativeNodeAnnouncementInfo { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -918,44 +960,44 @@ impl NodeAnnouncementInfo { /// Protocol features the node announced support for #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_get_features(this_ptr: &NodeAnnouncementInfo) -> crate::lightning::ln::features::NodeFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.features; - crate::lightning::ln::features::NodeFeatures { 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::NodeFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Protocol features the node announced support for #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_features(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::lightning::ln::features::NodeFeatures) { - 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()) }; } /// When the last known update to the node state was issued. /// Value is opaque, as set in the announcement. #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_get_last_update(this_ptr: &NodeAnnouncementInfo) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.last_update; + let mut inner_val = &mut this_ptr.get_native_mut_ref().last_update; *inner_val } /// When the last known update to the node state was issued. /// Value is opaque, as set in the announcement. #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_last_update(this_ptr: &mut NodeAnnouncementInfo, mut val: u32) { - unsafe { &mut *this_ptr.inner }.last_update = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.last_update = val; } /// Color assigned to the node #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_get_rgb(this_ptr: &NodeAnnouncementInfo) -> *const [u8; 3] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.rgb; + let mut inner_val = &mut this_ptr.get_native_mut_ref().rgb; inner_val } /// Color assigned to the node #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_rgb(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::c_types::ThreeBytes) { - unsafe { &mut *this_ptr.inner }.rgb = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.rgb = val.data; } /// Moniker assigned to the node. /// May be invalid or malicious (eg control chars), /// should not be exposed to the user. #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_get_alias(this_ptr: &NodeAnnouncementInfo) -> *const [u8; 32] { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.alias; + let mut inner_val = &mut this_ptr.get_native_mut_ref().alias; inner_val } /// Moniker assigned to the node. @@ -963,13 +1005,13 @@ pub extern "C" fn NodeAnnouncementInfo_get_alias(this_ptr: &NodeAnnouncementInfo /// should not be exposed to the user. #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_alias(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::c_types::ThirtyTwoBytes) { - unsafe { &mut *this_ptr.inner }.alias = val.data; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.alias = val.data; } /// Internet-level addresses via which one can connect to the node #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_addresses(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::c_types::derived::CVec_NetAddressZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item.into_native() }); }; - unsafe { &mut *this_ptr.inner }.addresses = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.addresses = local_val; } /// An initial announcement of the node /// Mostly redundant with the data we store in fields explicitly. @@ -979,8 +1021,8 @@ pub extern "C" fn NodeAnnouncementInfo_set_addresses(this_ptr: &mut NodeAnnounce /// 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 NodeAnnouncementInfo_get_announcement_message(this_ptr: &NodeAnnouncementInfo) -> crate::lightning::ln::msgs::NodeAnnouncement { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_message; - let mut local_inner_val = crate::lightning::ln::msgs::NodeAnnouncement { 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().announcement_message; + let mut local_inner_val = crate::lightning::ln::msgs::NodeAnnouncement { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// An initial announcement of the node @@ -992,7 +1034,7 @@ pub extern "C" fn NodeAnnouncementInfo_get_announcement_message(this_ptr: &NodeA #[no_mangle] pub extern "C" fn NodeAnnouncementInfo_set_announcement_message(this_ptr: &mut NodeAnnouncementInfo, mut val: crate::lightning::ln::msgs::NodeAnnouncement) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.announcement_message = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.announcement_message = local_val; } /// Constructs a new NodeAnnouncementInfo given each field #[must_use] @@ -1000,20 +1042,20 @@ pub extern "C" fn NodeAnnouncementInfo_set_announcement_message(this_ptr: &mut N pub extern "C" fn NodeAnnouncementInfo_new(mut features_arg: crate::lightning::ln::features::NodeFeatures, mut last_update_arg: u32, mut rgb_arg: crate::c_types::ThreeBytes, mut alias_arg: crate::c_types::ThirtyTwoBytes, mut addresses_arg: crate::c_types::derived::CVec_NetAddressZ, mut announcement_message_arg: crate::lightning::ln::msgs::NodeAnnouncement) -> NodeAnnouncementInfo { let mut local_addresses_arg = Vec::new(); for mut item in addresses_arg.into_rust().drain(..) { local_addresses_arg.push( { item.into_native() }); }; let mut local_announcement_message_arg = if announcement_message_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_message_arg.take_inner()) } }) }; - NodeAnnouncementInfo { inner: Box::into_raw(Box::new(nativeNodeAnnouncementInfo { + NodeAnnouncementInfo { inner: ObjOps::heap_alloc(nativeNodeAnnouncementInfo { features: *unsafe { Box::from_raw(features_arg.take_inner()) }, last_update: last_update_arg, rgb: rgb_arg.data, alias: alias_arg.data, addresses: local_addresses_arg, announcement_message: local_announcement_message_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for NodeAnnouncementInfo { fn clone(&self) -> Self { Self { inner: if <*mut nativeNodeAnnouncementInfo>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1031,7 +1073,7 @@ pub extern "C" fn NodeAnnouncementInfo_clone(orig: &NodeAnnouncementInfo) -> Nod #[no_mangle] /// Serialize the NodeAnnouncementInfo object into a byte array which can be read by NodeAnnouncementInfo_read pub extern "C" fn NodeAnnouncementInfo_write(obj: &NodeAnnouncementInfo) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn NodeAnnouncementInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1041,7 +1083,7 @@ pub(crate) extern "C" fn NodeAnnouncementInfo_write_void(obj: *const c_void) -> /// Read a NodeAnnouncementInfo from a byte array, created by NodeAnnouncementInfo_write pub extern "C" fn NodeAnnouncementInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeAnnouncementInfoDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NodeAnnouncementInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NodeAnnouncementInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -1067,7 +1109,7 @@ pub struct NodeInfo { impl Drop for NodeInfo { fn drop(&mut self) { if self.is_owned && !<*mut nativeNodeInfo>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1080,11 +1122,17 @@ extern "C" fn NodeInfo_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeNodeInfo); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl NodeInfo { + pub(crate) fn get_native_ref(&self) -> &'static nativeNodeInfo { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeNodeInfo { + 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 nativeNodeInfo { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1093,7 +1141,7 @@ impl NodeInfo { #[no_mangle] pub extern "C" fn NodeInfo_set_channels(this_ptr: &mut NodeInfo, mut val: crate::c_types::derived::CVec_u64Z) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; - unsafe { &mut *this_ptr.inner }.channels = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channels = local_val; } /// Lowest fees enabling routing via any of the enabled, known channels to a node. /// The two fields (flat and proportional fee) are independent, @@ -1102,8 +1150,8 @@ pub extern "C" fn NodeInfo_set_channels(this_ptr: &mut NodeInfo, mut val: crate: /// 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 NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo) -> crate::lightning::routing::network_graph::RoutingFees { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.lowest_inbound_channel_fees; - let mut local_inner_val = crate::lightning::routing::network_graph::RoutingFees { 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().lowest_inbound_channel_fees; + let mut local_inner_val = crate::lightning::routing::network_graph::RoutingFees { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// Lowest fees enabling routing via any of the enabled, known channels to a node. @@ -1114,7 +1162,7 @@ pub extern "C" fn NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo) #[no_mangle] pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeInfo, mut val: crate::lightning::routing::network_graph::RoutingFees) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.lowest_inbound_channel_fees = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.lowest_inbound_channel_fees = local_val; } /// More information about a node from node_announcement. /// Optional because we store a Node entry after learning about it from @@ -1123,8 +1171,8 @@ pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeIn /// 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 NodeInfo_get_announcement_info(this_ptr: &NodeInfo) -> crate::lightning::routing::network_graph::NodeAnnouncementInfo { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announcement_info; - let mut local_inner_val = crate::lightning::routing::network_graph::NodeAnnouncementInfo { 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().announcement_info; + let mut local_inner_val = crate::lightning::routing::network_graph::NodeAnnouncementInfo { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_inner_val } /// More information about a node from node_announcement. @@ -1135,7 +1183,7 @@ pub extern "C" fn NodeInfo_get_announcement_info(this_ptr: &NodeInfo) -> crate:: #[no_mangle] pub extern "C" fn NodeInfo_set_announcement_info(this_ptr: &mut NodeInfo, mut val: crate::lightning::routing::network_graph::NodeAnnouncementInfo) { let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *this_ptr.inner }.announcement_info = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.announcement_info = local_val; } /// Constructs a new NodeInfo given each field #[must_use] @@ -1144,17 +1192,17 @@ pub extern "C" fn NodeInfo_new(mut channels_arg: crate::c_types::derived::CVec_u let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { item }); }; let mut local_lowest_inbound_channel_fees_arg = if lowest_inbound_channel_fees_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(lowest_inbound_channel_fees_arg.take_inner()) } }) }; let mut local_announcement_info_arg = if announcement_info_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_info_arg.take_inner()) } }) }; - NodeInfo { inner: Box::into_raw(Box::new(nativeNodeInfo { + NodeInfo { inner: ObjOps::heap_alloc(nativeNodeInfo { channels: local_channels_arg, lowest_inbound_channel_fees: local_lowest_inbound_channel_fees_arg, announcement_info: local_announcement_info_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for NodeInfo { fn clone(&self) -> Self { Self { inner: if <*mut nativeNodeInfo>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1172,7 +1220,7 @@ pub extern "C" fn NodeInfo_clone(orig: &NodeInfo) -> NodeInfo { #[no_mangle] /// Serialize the NodeInfo object into a byte array which can be read by NodeInfo_read pub extern "C" fn NodeInfo_write(obj: &NodeInfo) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn NodeInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1182,13 +1230,13 @@ pub(crate) extern "C" fn NodeInfo_write_void(obj: *const c_void) -> crate::c_typ /// Read a NodeInfo from a byte array, created by NodeInfo_write pub extern "C" fn NodeInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NodeInfoDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NodeInfo { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NodeInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } #[no_mangle] /// Serialize the NetworkGraph object into a byte array which can be read by NetworkGraph_read pub extern "C" fn NetworkGraph_write(obj: &NetworkGraph) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn NetworkGraph_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -1198,7 +1246,7 @@ pub(crate) extern "C" fn NetworkGraph_write_void(obj: *const c_void) -> crate::c /// Read a NetworkGraph from a byte array, created by NetworkGraph_write pub extern "C" fn NetworkGraph_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NetworkGraphDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NetworkGraph { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::network_graph::NetworkGraph { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } /// Creates a new, empty, network graph. @@ -1206,7 +1254,7 @@ pub extern "C" fn NetworkGraph_read(ser: crate::c_types::u8slice) -> crate::c_ty #[no_mangle] pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes) -> crate::lightning::routing::network_graph::NetworkGraph { let mut ret = lightning::routing::network_graph::NetworkGraph::new(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap()); - crate::lightning::routing::network_graph::NetworkGraph { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning::routing::network_graph::NetworkGraph { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// For an already known node (from channel announcements), update its stored properties from a @@ -1218,8 +1266,8 @@ pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBy #[must_use] #[no_mangle] pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_announcement(unsafe { &*msg.inner }, secp256k1::SECP256K1); - 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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_announcement(msg.get_native_ref(), secp256k1::SECP256K1); + 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 } @@ -1230,8 +1278,8 @@ pub extern "C" fn NetworkGraph_update_node_from_announcement(this_arg: &mut Netw #[must_use] #[no_mangle] pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedNodeAnnouncement) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_unsigned_announcement(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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_node_from_unsigned_announcement(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 } @@ -1249,8 +1297,8 @@ pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: #[no_mangle] pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelAnnouncement, chain_access: *mut crate::lightning::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_announcement(unsafe { &*msg.inner }, &local_chain_access, secp256k1::SECP256K1); - 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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_announcement(msg.get_native_ref(), &local_chain_access, secp256k1::SECP256K1); + 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 } @@ -1266,8 +1314,8 @@ pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &mut N #[no_mangle] pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement, chain_access: *mut crate::lightning::chain::Access) -> crate::c_types::derived::CResult_NoneLightningErrorZ { let mut local_chain_access = if chain_access == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_access) } }) }; - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_unsigned_announcement(unsafe { &*msg.inner }, &local_chain_access); - 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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_from_unsigned_announcement(msg.get_native_ref(), &local_chain_access); + 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 } @@ -1277,7 +1325,7 @@ pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_ar /// If not permanent, makes channels unavailable for routing. #[no_mangle] pub extern "C" fn NetworkGraph_close_channel_from_update(this_arg: &mut NetworkGraph, mut short_channel_id: u64, mut is_permanent: bool) { - unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.close_channel_from_update(short_channel_id, is_permanent) + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.close_channel_from_update(short_channel_id, is_permanent) } /// For an already known (from announcement) channel, update info about one of the directions @@ -1289,8 +1337,8 @@ pub extern "C" fn NetworkGraph_close_channel_from_update(this_arg: &mut NetworkG #[must_use] #[no_mangle] pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel(unsafe { &*msg.inner }, secp256k1::SECP256K1); - 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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel(msg.get_native_ref(), secp256k1::SECP256K1); + 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 } @@ -1300,8 +1348,8 @@ pub extern "C" fn NetworkGraph_update_channel(this_arg: &mut NetworkGraph, msg: #[must_use] #[no_mangle] pub extern "C" fn NetworkGraph_update_channel_unsigned(this_arg: &mut NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelUpdate) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut ret = unsafe { &mut (*(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_unsigned(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 = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeNetworkGraph)) }.update_channel_unsigned(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 } diff --git a/lightning-c-bindings/src/lightning/routing/router.rs b/lightning-c-bindings/src/lightning/routing/router.rs index ad15a35..7b017f4 100644 --- a/lightning-c-bindings/src/lightning/routing/router.rs +++ b/lightning-c-bindings/src/lightning/routing/router.rs @@ -39,7 +39,7 @@ pub struct RouteHop { impl Drop for RouteHop { fn drop(&mut self) { if self.is_owned && !<*mut nativeRouteHop>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -52,11 +52,17 @@ extern "C" fn RouteHop_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRouteHop); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RouteHop { + pub(crate) fn get_native_ref(&self) -> &'static nativeRouteHop { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRouteHop { + 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 nativeRouteHop { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -64,57 +70,57 @@ impl RouteHop { /// The node_id of the node at this hop. #[no_mangle] pub extern "C" fn RouteHop_get_pubkey(this_ptr: &RouteHop) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().pubkey; crate::c_types::PublicKey::from_rust(&inner_val) } /// The node_id of the node at this hop. #[no_mangle] pub extern "C" fn RouteHop_set_pubkey(this_ptr: &mut RouteHop, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.pubkey = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.pubkey = val.into_rust(); } /// The node_announcement features of the node at this hop. For the last hop, these may be /// amended to match the features present in the invoice this node generated. #[no_mangle] pub extern "C" fn RouteHop_get_node_features(this_ptr: &RouteHop) -> crate::lightning::ln::features::NodeFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.node_features; - crate::lightning::ln::features::NodeFeatures { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_features; + crate::lightning::ln::features::NodeFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The node_announcement features of the node at this hop. For the last hop, these may be /// amended to match the features present in the invoice this node generated. #[no_mangle] pub extern "C" fn RouteHop_set_node_features(this_ptr: &mut RouteHop, mut val: crate::lightning::ln::features::NodeFeatures) { - unsafe { &mut *this_ptr.inner }.node_features = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_features = *unsafe { Box::from_raw(val.take_inner()) }; } /// The channel that should be used from the previous hop to reach this node. #[no_mangle] pub extern "C" fn RouteHop_get_short_channel_id(this_ptr: &RouteHop) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; *inner_val } /// The channel that should be used from the previous hop to reach this node. #[no_mangle] pub extern "C" fn RouteHop_set_short_channel_id(this_ptr: &mut RouteHop, mut val: u64) { - unsafe { &mut *this_ptr.inner }.short_channel_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } /// The channel_announcement features of the channel that should be used from the previous hop /// to reach this node. #[no_mangle] pub extern "C" fn RouteHop_get_channel_features(this_ptr: &RouteHop) -> crate::lightning::ln::features::ChannelFeatures { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_features; - crate::lightning::ln::features::ChannelFeatures { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_features; + crate::lightning::ln::features::ChannelFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The channel_announcement features of the channel that should be used from the previous hop /// to reach this node. #[no_mangle] pub extern "C" fn RouteHop_set_channel_features(this_ptr: &mut RouteHop, mut val: crate::lightning::ln::features::ChannelFeatures) { - unsafe { &mut *this_ptr.inner }.channel_features = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_features = *unsafe { Box::from_raw(val.take_inner()) }; } /// The fee taken on this hop (for paying for the use of the *next* channel in the path). /// For the last hop, this should be the full value of the payment (might be more than /// requested if we had to match htlc_minimum_msat). #[no_mangle] pub extern "C" fn RouteHop_get_fee_msat(this_ptr: &RouteHop) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_msat; *inner_val } /// The fee taken on this hop (for paying for the use of the *next* channel in the path). @@ -122,39 +128,39 @@ pub extern "C" fn RouteHop_get_fee_msat(this_ptr: &RouteHop) -> u64 { /// requested if we had to match htlc_minimum_msat). #[no_mangle] pub extern "C" fn RouteHop_set_fee_msat(this_ptr: &mut RouteHop, mut val: u64) { - unsafe { &mut *this_ptr.inner }.fee_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_msat = val; } /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value /// expected at the destination, in excess of the current block height. #[no_mangle] pub extern "C" fn RouteHop_get_cltv_expiry_delta(this_ptr: &RouteHop) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry_delta; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; *inner_val } /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value /// expected at the destination, in excess of the current block height. #[no_mangle] pub extern "C" fn RouteHop_set_cltv_expiry_delta(this_ptr: &mut RouteHop, mut val: u32) { - unsafe { &mut *this_ptr.inner }.cltv_expiry_delta = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; } /// Constructs a new RouteHop given each field #[must_use] #[no_mangle] pub extern "C" fn RouteHop_new(mut pubkey_arg: crate::c_types::PublicKey, mut node_features_arg: crate::lightning::ln::features::NodeFeatures, mut short_channel_id_arg: u64, mut channel_features_arg: crate::lightning::ln::features::ChannelFeatures, mut fee_msat_arg: u64, mut cltv_expiry_delta_arg: u32) -> RouteHop { - RouteHop { inner: Box::into_raw(Box::new(nativeRouteHop { + RouteHop { inner: ObjOps::heap_alloc(nativeRouteHop { pubkey: pubkey_arg.into_rust(), node_features: *unsafe { Box::from_raw(node_features_arg.take_inner()) }, short_channel_id: short_channel_id_arg, channel_features: *unsafe { Box::from_raw(channel_features_arg.take_inner()) }, fee_msat: fee_msat_arg, cltv_expiry_delta: cltv_expiry_delta_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for RouteHop { fn clone(&self) -> Self { Self { inner: if <*mut nativeRouteHop>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -172,7 +178,7 @@ pub extern "C" fn RouteHop_clone(orig: &RouteHop) -> RouteHop { #[no_mangle] /// Serialize the RouteHop object into a byte array which can be read by RouteHop_read pub extern "C" fn RouteHop_write(obj: &RouteHop) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn RouteHop_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -182,7 +188,7 @@ pub(crate) extern "C" fn RouteHop_write_void(obj: *const c_void) -> crate::c_typ /// Read a RouteHop from a byte array, created by RouteHop_write pub extern "C" fn RouteHop_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RouteHopDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::RouteHop { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::RouteHop { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -209,7 +215,7 @@ pub struct Route { impl Drop for Route { fn drop(&mut self) { if self.is_owned && !<*mut nativeRoute>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -222,11 +228,17 @@ extern "C" fn Route_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRoute); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Route { + pub(crate) fn get_native_ref(&self) -> &'static nativeRoute { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRoute { + 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 nativeRoute { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -240,22 +252,22 @@ impl Route { #[no_mangle] pub extern "C" fn Route_set_paths(this_ptr: &mut Route, mut val: crate::c_types::derived::CVec_CVec_RouteHopZZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { let mut local_val_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_val_0.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_val_0 }); }; - unsafe { &mut *this_ptr.inner }.paths = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.paths = local_val; } /// Constructs a new Route given each field #[must_use] #[no_mangle] pub extern "C" fn Route_new(mut paths_arg: crate::c_types::derived::CVec_CVec_RouteHopZZ) -> Route { let mut local_paths_arg = Vec::new(); for mut item in paths_arg.into_rust().drain(..) { local_paths_arg.push( { let mut local_paths_arg_0 = Vec::new(); for mut item in item.into_rust().drain(..) { local_paths_arg_0.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; local_paths_arg_0 }); }; - Route { inner: Box::into_raw(Box::new(nativeRoute { + Route { inner: ObjOps::heap_alloc(nativeRoute { paths: local_paths_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for Route { fn clone(&self) -> Self { Self { inner: if <*mut nativeRoute>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -273,7 +285,7 @@ pub extern "C" fn Route_clone(orig: &Route) -> Route { #[no_mangle] /// Serialize the Route object into a byte array which can be read by Route_read pub extern "C" fn Route_write(obj: &Route) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn Route_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -283,7 +295,7 @@ pub(crate) extern "C" fn Route_write_void(obj: *const c_void) -> crate::c_types: /// Read a Route from a byte array, created by Route_write pub extern "C" fn Route_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_RouteDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -309,7 +321,7 @@ pub struct RouteHint { impl Drop for RouteHint { fn drop(&mut self) { if self.is_owned && !<*mut nativeRouteHint>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -322,11 +334,17 @@ extern "C" fn RouteHint_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRouteHint); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RouteHint { + pub(crate) fn get_native_ref(&self) -> &'static nativeRouteHint { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRouteHint { + 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 nativeRouteHint { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -338,13 +356,13 @@ impl RouteHint { pub extern "C" fn RouteHint_eq(a: &RouteHint, b: &RouteHint) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RouteHint { fn clone(&self) -> Self { Self { inner: if <*mut nativeRouteHint>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -382,7 +400,7 @@ pub struct RouteHintHop { impl Drop for RouteHintHop { fn drop(&mut self) { if self.is_owned && !<*mut nativeRouteHintHop>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -395,11 +413,17 @@ extern "C" fn RouteHintHop_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRouteHintHop); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RouteHintHop { + pub(crate) fn get_native_ref(&self) -> &'static nativeRouteHintHop { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRouteHintHop { + 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 nativeRouteHintHop { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -407,51 +431,51 @@ impl RouteHintHop { /// The node_id of the non-target end of the route #[no_mangle] pub extern "C" fn RouteHintHop_get_src_node_id(this_ptr: &RouteHintHop) -> crate::c_types::PublicKey { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.src_node_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().src_node_id; crate::c_types::PublicKey::from_rust(&inner_val) } /// The node_id of the non-target end of the route #[no_mangle] pub extern "C" fn RouteHintHop_set_src_node_id(this_ptr: &mut RouteHintHop, mut val: crate::c_types::PublicKey) { - unsafe { &mut *this_ptr.inner }.src_node_id = val.into_rust(); + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.src_node_id = val.into_rust(); } /// The short_channel_id of this channel #[no_mangle] pub extern "C" fn RouteHintHop_get_short_channel_id(this_ptr: &RouteHintHop) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id; + let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id; *inner_val } /// The short_channel_id of this channel #[no_mangle] pub extern "C" fn RouteHintHop_set_short_channel_id(this_ptr: &mut RouteHintHop, mut val: u64) { - unsafe { &mut *this_ptr.inner }.short_channel_id = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } /// The fees which must be paid to use this channel #[no_mangle] pub extern "C" fn RouteHintHop_get_fees(this_ptr: &RouteHintHop) -> crate::lightning::routing::network_graph::RoutingFees { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fees; - crate::lightning::routing::network_graph::RoutingFees { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().fees; + crate::lightning::routing::network_graph::RoutingFees { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// The fees which must be paid to use this channel #[no_mangle] pub extern "C" fn RouteHintHop_set_fees(this_ptr: &mut RouteHintHop, mut val: crate::lightning::routing::network_graph::RoutingFees) { - unsafe { &mut *this_ptr.inner }.fees = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fees = *unsafe { Box::from_raw(val.take_inner()) }; } /// The difference in CLTV values between this node and the next node. #[no_mangle] pub extern "C" fn RouteHintHop_get_cltv_expiry_delta(this_ptr: &RouteHintHop) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry_delta; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; *inner_val } /// The difference in CLTV values between this node and the next node. #[no_mangle] pub extern "C" fn RouteHintHop_set_cltv_expiry_delta(this_ptr: &mut RouteHintHop, mut val: u16) { - unsafe { &mut *this_ptr.inner }.cltv_expiry_delta = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; } /// The minimum value, in msat, which must be relayed to the next hop. #[no_mangle] pub extern "C" fn RouteHintHop_get_htlc_minimum_msat(this_ptr: &RouteHintHop) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().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 } @@ -459,12 +483,12 @@ pub extern "C" fn RouteHintHop_get_htlc_minimum_msat(this_ptr: &RouteHintHop) -> #[no_mangle] pub extern "C" fn RouteHintHop_set_htlc_minimum_msat(this_ptr: &mut RouteHintHop, 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 }.htlc_minimum_msat = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = local_val; } /// The maximum value in msat available for routing with a single HTLC. #[no_mangle] pub extern "C" fn RouteHintHop_get_htlc_maximum_msat(this_ptr: &RouteHintHop) -> crate::c_types::derived::COption_u64Z { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.htlc_maximum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().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 } @@ -472,7 +496,7 @@ pub extern "C" fn RouteHintHop_get_htlc_maximum_msat(this_ptr: &RouteHintHop) -> #[no_mangle] pub extern "C" fn RouteHintHop_set_htlc_maximum_msat(this_ptr: &mut RouteHintHop, 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 }.htlc_maximum_msat = local_val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_maximum_msat = local_val; } /// Constructs a new RouteHintHop given each field #[must_use] @@ -480,14 +504,14 @@ pub extern "C" fn RouteHintHop_set_htlc_maximum_msat(this_ptr: &mut RouteHintHop pub extern "C" fn RouteHintHop_new(mut src_node_id_arg: crate::c_types::PublicKey, mut short_channel_id_arg: u64, mut fees_arg: crate::lightning::routing::network_graph::RoutingFees, mut cltv_expiry_delta_arg: u16, mut htlc_minimum_msat_arg: crate::c_types::derived::COption_u64Z, mut htlc_maximum_msat_arg: crate::c_types::derived::COption_u64Z) -> RouteHintHop { let mut local_htlc_minimum_msat_arg = if htlc_minimum_msat_arg.is_some() { Some( { htlc_minimum_msat_arg.take() }) } else { None }; let mut local_htlc_maximum_msat_arg = if htlc_maximum_msat_arg.is_some() { Some( { htlc_maximum_msat_arg.take() }) } else { None }; - RouteHintHop { inner: Box::into_raw(Box::new(nativeRouteHintHop { + RouteHintHop { inner: ObjOps::heap_alloc(nativeRouteHintHop { src_node_id: src_node_id_arg.into_rust(), short_channel_id: short_channel_id_arg, fees: *unsafe { Box::from_raw(fees_arg.take_inner()) }, cltv_expiry_delta: cltv_expiry_delta_arg, htlc_minimum_msat: local_htlc_minimum_msat_arg, htlc_maximum_msat: local_htlc_maximum_msat_arg, - })), is_owned: true } + }), is_owned: true } } /// Checks if two RouteHintHops contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -496,13 +520,13 @@ pub extern "C" fn RouteHintHop_new(mut src_node_id_arg: crate::c_types::PublicKe pub extern "C" fn RouteHintHop_eq(a: &RouteHintHop, b: &RouteHintHop) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RouteHintHop { fn clone(&self) -> Self { Self { inner: if <*mut nativeRouteHintHop>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -524,10 +548,10 @@ pub extern "C" fn RouteHintHop_clone(orig: &RouteHintHop) -> RouteHintHop { /// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] pub extern "C" fn get_keysend_route(mut our_node_id: crate::c_types::PublicKey, network: &crate::lightning::routing::network_graph::NetworkGraph, mut payee: crate::c_types::PublicKey, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut last_hops: crate::c_types::derived::CVec_RouteHintZ, mut final_value_msat: u64, mut final_cltv: u32, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_RouteLightningErrorZ { - let mut local_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { unsafe { &*item.inner } }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); - let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { unsafe { &*item.inner } }); }; - let mut ret = lightning::routing::router::get_keysend_route(&our_node_id.into_rust(), unsafe { &*network.inner }, &payee.into_rust(), local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { item.get_native_ref() }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); + let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { item.get_native_ref() }); }; + let mut ret = lightning::routing::router::get_keysend_route(&our_node_id.into_rust(), network.get_native_ref(), &payee.into_rust(), local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: ObjOps::heap_alloc(o), is_owned: true } }).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 } @@ -556,10 +580,10 @@ pub extern "C" fn get_keysend_route(mut our_node_id: crate::c_types::PublicKey, #[no_mangle] pub extern "C" fn get_route(mut our_node_id: crate::c_types::PublicKey, network: &crate::lightning::routing::network_graph::NetworkGraph, mut payee: crate::c_types::PublicKey, mut payee_features: crate::lightning::ln::features::InvoiceFeatures, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut last_hops: crate::c_types::derived::CVec_RouteHintZ, mut final_value_msat: u64, mut final_cltv: u32, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_RouteLightningErrorZ { let mut local_payee_features = if payee_features.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payee_features.take_inner()) } }) }; - let mut local_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { unsafe { &*item.inner } }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); - let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { unsafe { &*item.inner } }); }; - let mut ret = lightning::routing::router::get_route(&our_node_id.into_rust(), unsafe { &*network.inner }, &payee.into_rust(), local_payee_features, local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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_first_hops_base = if first_hops == std::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { item.get_native_ref() }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); + let mut local_last_hops = Vec::new(); for mut item in last_hops.as_slice().iter() { local_last_hops.push( { item.get_native_ref() }); }; + let mut ret = lightning::routing::router::get_route(&our_node_id.into_rust(), network.get_native_ref(), &payee.into_rust(), local_payee_features, local_first_hops, &local_last_hops[..], final_value_msat, final_cltv, logger); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: ObjOps::heap_alloc(o), is_owned: true } }).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 } diff --git a/lightning-c-bindings/src/lightning/util/config.rs b/lightning-c-bindings/src/lightning/util/config.rs index df0220e..5e042c8 100644 --- a/lightning-c-bindings/src/lightning/util/config.rs +++ b/lightning-c-bindings/src/lightning/util/config.rs @@ -39,7 +39,7 @@ pub struct ChannelHandshakeConfig { impl Drop for ChannelHandshakeConfig { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelHandshakeConfig>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -52,11 +52,17 @@ extern "C" fn ChannelHandshakeConfig_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelHandshakeConfig); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelHandshakeConfig { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelHandshakeConfig { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelHandshakeConfig { + 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 nativeChannelHandshakeConfig { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -68,7 +74,7 @@ impl ChannelHandshakeConfig { /// Default value: 6. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_get_minimum_depth(this_ptr: &ChannelHandshakeConfig) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.minimum_depth; + let mut inner_val = &mut this_ptr.get_native_mut_ref().minimum_depth; *inner_val } /// Confirmations we will wait for before considering the channel locked in. @@ -78,7 +84,7 @@ pub extern "C" fn ChannelHandshakeConfig_get_minimum_depth(this_ptr: &ChannelHan /// Default value: 6. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_set_minimum_depth(this_ptr: &mut ChannelHandshakeConfig, mut val: u32) { - unsafe { &mut *this_ptr.inner }.minimum_depth = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.minimum_depth = val; } /// Set to the number of blocks we require our counterparty to wait to claim their money (ie /// the number of blocks we have to punish our counterparty if they broadcast a revoked @@ -97,7 +103,7 @@ pub extern "C" fn ChannelHandshakeConfig_set_minimum_depth(this_ptr: &mut Channe /// can tweak config to ask for more security, not less. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_get_our_to_self_delay(this_ptr: &ChannelHandshakeConfig) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.our_to_self_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().our_to_self_delay; *inner_val } /// Set to the number of blocks we require our counterparty to wait to claim their money (ie @@ -117,7 +123,7 @@ pub extern "C" fn ChannelHandshakeConfig_get_our_to_self_delay(this_ptr: &Channe /// can tweak config to ask for more security, not less. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_set_our_to_self_delay(this_ptr: &mut ChannelHandshakeConfig, mut val: u16) { - unsafe { &mut *this_ptr.inner }.our_to_self_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.our_to_self_delay = val; } /// Set to the smallest value HTLC we will accept to process. /// @@ -128,7 +134,7 @@ pub extern "C" fn ChannelHandshakeConfig_set_our_to_self_delay(this_ptr: &mut Ch /// by the protocol. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_get_our_htlc_minimum_msat(this_ptr: &ChannelHandshakeConfig) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.our_htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().our_htlc_minimum_msat; *inner_val } /// Set to the smallest value HTLC we will accept to process. @@ -140,23 +146,23 @@ pub extern "C" fn ChannelHandshakeConfig_get_our_htlc_minimum_msat(this_ptr: &Ch /// by the protocol. #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_set_our_htlc_minimum_msat(this_ptr: &mut ChannelHandshakeConfig, mut val: u64) { - unsafe { &mut *this_ptr.inner }.our_htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.our_htlc_minimum_msat = val; } /// Constructs a new ChannelHandshakeConfig given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_new(mut minimum_depth_arg: u32, mut our_to_self_delay_arg: u16, mut our_htlc_minimum_msat_arg: u64) -> ChannelHandshakeConfig { - ChannelHandshakeConfig { inner: Box::into_raw(Box::new(nativeChannelHandshakeConfig { + ChannelHandshakeConfig { inner: ObjOps::heap_alloc(nativeChannelHandshakeConfig { minimum_depth: minimum_depth_arg, our_to_self_delay: our_to_self_delay_arg, our_htlc_minimum_msat: our_htlc_minimum_msat_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelHandshakeConfig { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelHandshakeConfig>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -175,7 +181,7 @@ pub extern "C" fn ChannelHandshakeConfig_clone(orig: &ChannelHandshakeConfig) -> #[must_use] #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_default() -> ChannelHandshakeConfig { - ChannelHandshakeConfig { inner: Box::into_raw(Box::new(Default::default())), is_owned: true } + ChannelHandshakeConfig { inner: ObjOps::heap_alloc(Default::default()), is_owned: true } } use lightning::util::config::ChannelHandshakeLimits as nativeChannelHandshakeLimitsImport; @@ -210,7 +216,7 @@ pub struct ChannelHandshakeLimits { impl Drop for ChannelHandshakeLimits { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelHandshakeLimits>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -223,11 +229,17 @@ extern "C" fn ChannelHandshakeLimits_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelHandshakeLimits); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelHandshakeLimits { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelHandshakeLimits { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelHandshakeLimits { + 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 nativeChannelHandshakeLimits { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -238,7 +250,7 @@ impl ChannelHandshakeLimits { /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_min_funding_satoshis(this_ptr: &ChannelHandshakeLimits) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.min_funding_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().min_funding_satoshis; *inner_val } /// Minimum allowed satoshis when a channel is funded, this is supplied by the sender and so @@ -247,7 +259,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_min_funding_satoshis(this_ptr: &Cha /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_min_funding_satoshis(this_ptr: &mut ChannelHandshakeLimits, mut val: u64) { - unsafe { &mut *this_ptr.inner }.min_funding_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.min_funding_satoshis = val; } /// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows /// you to limit the maximum minimum-size they can require. @@ -255,7 +267,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_min_funding_satoshis(this_ptr: &mut /// Default value: u64::max_value. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_max_htlc_minimum_msat(this_ptr: &ChannelHandshakeLimits) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_htlc_minimum_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_htlc_minimum_msat; *inner_val } /// The remote node sets a limit on the minimum size of HTLCs we can send to them. This allows @@ -264,7 +276,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_max_htlc_minimum_msat(this_ptr: &Ch /// Default value: u64::max_value. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_max_htlc_minimum_msat(this_ptr: &mut ChannelHandshakeLimits, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_htlc_minimum_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_htlc_minimum_msat = val; } /// The remote node sets a limit on the maximum value of pending HTLCs to them at any given /// time to limit their funds exposure to HTLCs. This allows you to set a minimum such value. @@ -272,7 +284,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_max_htlc_minimum_msat(this_ptr: &mu /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_min_max_htlc_value_in_flight_msat(this_ptr: &ChannelHandshakeLimits) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.min_max_htlc_value_in_flight_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().min_max_htlc_value_in_flight_msat; *inner_val } /// The remote node sets a limit on the maximum value of pending HTLCs to them at any given @@ -281,7 +293,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_min_max_htlc_value_in_flight_msat(t /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_min_max_htlc_value_in_flight_msat(this_ptr: &mut ChannelHandshakeLimits, mut val: u64) { - unsafe { &mut *this_ptr.inner }.min_max_htlc_value_in_flight_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.min_max_htlc_value_in_flight_msat = val; } /// The remote node will require we keep a certain amount in direct payment to ourselves at all /// time, ensuring that we are able to be punished if we broadcast an old state. This allows to @@ -290,7 +302,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_min_max_htlc_value_in_flight_msat(t /// Default value: u64::max_value. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_max_channel_reserve_satoshis(this_ptr: &ChannelHandshakeLimits) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_channel_reserve_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_channel_reserve_satoshis; *inner_val } /// The remote node will require we keep a certain amount in direct payment to ourselves at all @@ -300,7 +312,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_max_channel_reserve_satoshis(this_p /// Default value: u64::max_value. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_max_channel_reserve_satoshis(this_ptr: &mut ChannelHandshakeLimits, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_channel_reserve_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_channel_reserve_satoshis = val; } /// The remote node sets a limit on the maximum number of pending HTLCs to them at any given /// time. This allows you to set a minimum such value. @@ -308,7 +320,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_max_channel_reserve_satoshis(this_p /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_min_max_accepted_htlcs(this_ptr: &ChannelHandshakeLimits) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.min_max_accepted_htlcs; + let mut inner_val = &mut this_ptr.get_native_mut_ref().min_max_accepted_htlcs; *inner_val } /// The remote node sets a limit on the maximum number of pending HTLCs to them at any given @@ -317,7 +329,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_min_max_accepted_htlcs(this_ptr: &C /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_min_max_accepted_htlcs(this_ptr: &mut ChannelHandshakeLimits, mut val: u16) { - unsafe { &mut *this_ptr.inner }.min_max_accepted_htlcs = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.min_max_accepted_htlcs = val; } /// Before a channel is usable the funding transaction will need to be confirmed by at least a /// certain number of blocks, specified by the node which is not the funder (as the funder can @@ -327,7 +339,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_min_max_accepted_htlcs(this_ptr: &m /// Default value: 144, or roughly one day and only applies to outbound channels. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_max_minimum_depth(this_ptr: &ChannelHandshakeLimits) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_minimum_depth; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_minimum_depth; *inner_val } /// Before a channel is usable the funding transaction will need to be confirmed by at least a @@ -338,7 +350,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_max_minimum_depth(this_ptr: &Channe /// Default value: 144, or roughly one day and only applies to outbound channels. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_max_minimum_depth(this_ptr: &mut ChannelHandshakeLimits, mut val: u32) { - unsafe { &mut *this_ptr.inner }.max_minimum_depth = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_minimum_depth = val; } /// Set to force an incoming channel to match our announced channel preference in /// [`ChannelConfig::announced_channel`]. @@ -350,7 +362,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_max_minimum_depth(this_ptr: &mut Ch /// Default value: true. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_force_announced_channel_preference(this_ptr: &ChannelHandshakeLimits) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.force_announced_channel_preference; + let mut inner_val = &mut this_ptr.get_native_mut_ref().force_announced_channel_preference; *inner_val } /// Set to force an incoming channel to match our announced channel preference in @@ -363,7 +375,7 @@ pub extern "C" fn ChannelHandshakeLimits_get_force_announced_channel_preference( /// Default value: true. #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_force_announced_channel_preference(this_ptr: &mut ChannelHandshakeLimits, mut val: bool) { - unsafe { &mut *this_ptr.inner }.force_announced_channel_preference = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.force_announced_channel_preference = val; } /// Set to the amount of time we're willing to wait to claim money back to us. /// @@ -374,7 +386,7 @@ pub extern "C" fn ChannelHandshakeLimits_set_force_announced_channel_preference( /// reduce the loss of having useless locked funds (if your peer accepts) #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_get_their_to_self_delay(this_ptr: &ChannelHandshakeLimits) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.their_to_self_delay; + let mut inner_val = &mut this_ptr.get_native_mut_ref().their_to_self_delay; *inner_val } /// Set to the amount of time we're willing to wait to claim money back to us. @@ -386,13 +398,13 @@ pub extern "C" fn ChannelHandshakeLimits_get_their_to_self_delay(this_ptr: &Chan /// reduce the loss of having useless locked funds (if your peer accepts) #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_set_their_to_self_delay(this_ptr: &mut ChannelHandshakeLimits, mut val: u16) { - unsafe { &mut *this_ptr.inner }.their_to_self_delay = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.their_to_self_delay = val; } /// Constructs a new ChannelHandshakeLimits given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_new(mut min_funding_satoshis_arg: u64, mut max_htlc_minimum_msat_arg: u64, mut min_max_htlc_value_in_flight_msat_arg: u64, mut max_channel_reserve_satoshis_arg: u64, mut min_max_accepted_htlcs_arg: u16, mut max_minimum_depth_arg: u32, mut force_announced_channel_preference_arg: bool, mut their_to_self_delay_arg: u16) -> ChannelHandshakeLimits { - ChannelHandshakeLimits { inner: Box::into_raw(Box::new(nativeChannelHandshakeLimits { + ChannelHandshakeLimits { inner: ObjOps::heap_alloc(nativeChannelHandshakeLimits { min_funding_satoshis: min_funding_satoshis_arg, max_htlc_minimum_msat: max_htlc_minimum_msat_arg, min_max_htlc_value_in_flight_msat: min_max_htlc_value_in_flight_msat_arg, @@ -401,13 +413,13 @@ pub extern "C" fn ChannelHandshakeLimits_new(mut min_funding_satoshis_arg: u64, max_minimum_depth: max_minimum_depth_arg, force_announced_channel_preference: force_announced_channel_preference_arg, their_to_self_delay: their_to_self_delay_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelHandshakeLimits { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelHandshakeLimits>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -426,7 +438,7 @@ pub extern "C" fn ChannelHandshakeLimits_clone(orig: &ChannelHandshakeLimits) -> #[must_use] #[no_mangle] pub extern "C" fn ChannelHandshakeLimits_default() -> ChannelHandshakeLimits { - ChannelHandshakeLimits { inner: Box::into_raw(Box::new(Default::default())), is_owned: true } + ChannelHandshakeLimits { inner: ObjOps::heap_alloc(Default::default()), is_owned: true } } use lightning::util::config::ChannelConfig as nativeChannelConfigImport; @@ -452,7 +464,7 @@ pub struct ChannelConfig { impl Drop for ChannelConfig { fn drop(&mut self) { if self.is_owned && !<*mut nativeChannelConfig>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -465,11 +477,17 @@ extern "C" fn ChannelConfig_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelConfig); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ChannelConfig { + pub(crate) fn get_native_ref(&self) -> &'static nativeChannelConfig { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelConfig { + 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 nativeChannelConfig { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -482,7 +500,7 @@ impl ChannelConfig { /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelConfig_get_forwarding_fee_proportional_millionths(this_ptr: &ChannelConfig) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.forwarding_fee_proportional_millionths; + let mut inner_val = &mut this_ptr.get_native_mut_ref().forwarding_fee_proportional_millionths; *inner_val } /// Amount (in millionths of a satoshi) charged per satoshi for payments forwarded outbound @@ -493,7 +511,7 @@ pub extern "C" fn ChannelConfig_get_forwarding_fee_proportional_millionths(this_ /// Default value: 0. #[no_mangle] pub extern "C" fn ChannelConfig_set_forwarding_fee_proportional_millionths(this_ptr: &mut ChannelConfig, mut val: u32) { - unsafe { &mut *this_ptr.inner }.forwarding_fee_proportional_millionths = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.forwarding_fee_proportional_millionths = val; } /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in /// excess of [`forwarding_fee_proportional_millionths`]. @@ -509,7 +527,7 @@ pub extern "C" fn ChannelConfig_set_forwarding_fee_proportional_millionths(this_ /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths #[no_mangle] pub extern "C" fn ChannelConfig_get_forwarding_fee_base_msat(this_ptr: &ChannelConfig) -> u32 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.forwarding_fee_base_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().forwarding_fee_base_msat; *inner_val } /// Amount (in milli-satoshi) charged for payments forwarded outbound over the channel, in @@ -526,7 +544,7 @@ pub extern "C" fn ChannelConfig_get_forwarding_fee_base_msat(this_ptr: &ChannelC /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths #[no_mangle] pub extern "C" fn ChannelConfig_set_forwarding_fee_base_msat(this_ptr: &mut ChannelConfig, mut val: u32) { - unsafe { &mut *this_ptr.inner }.forwarding_fee_base_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.forwarding_fee_base_msat = val; } /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over /// the channel this config applies to. @@ -549,7 +567,7 @@ pub extern "C" fn ChannelConfig_set_forwarding_fee_base_msat(this_ptr: &mut Chan /// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA #[no_mangle] pub extern "C" fn ChannelConfig_get_cltv_expiry_delta(this_ptr: &ChannelConfig) -> u16 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.cltv_expiry_delta; + let mut inner_val = &mut this_ptr.get_native_mut_ref().cltv_expiry_delta; *inner_val } /// The difference in the CLTV value between incoming HTLCs and an outbound HTLC forwarded over @@ -573,7 +591,7 @@ pub extern "C" fn ChannelConfig_get_cltv_expiry_delta(this_ptr: &ChannelConfig) /// [`MIN_CLTV_EXPIRY_DELTA`]: crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA #[no_mangle] pub extern "C" fn ChannelConfig_set_cltv_expiry_delta(this_ptr: &mut ChannelConfig, mut val: u16) { - unsafe { &mut *this_ptr.inner }.cltv_expiry_delta = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.cltv_expiry_delta = val; } /// Set to announce the channel publicly and notify all nodes that they can route via this /// channel. @@ -588,7 +606,7 @@ pub extern "C" fn ChannelConfig_set_cltv_expiry_delta(this_ptr: &mut ChannelConf /// Default value: false. #[no_mangle] pub extern "C" fn ChannelConfig_get_announced_channel(this_ptr: &ChannelConfig) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.announced_channel; + let mut inner_val = &mut this_ptr.get_native_mut_ref().announced_channel; *inner_val } /// Set to announce the channel publicly and notify all nodes that they can route via this @@ -604,7 +622,7 @@ pub extern "C" fn ChannelConfig_get_announced_channel(this_ptr: &ChannelConfig) /// Default value: false. #[no_mangle] pub extern "C" fn ChannelConfig_set_announced_channel(this_ptr: &mut ChannelConfig, mut val: bool) { - unsafe { &mut *this_ptr.inner }.announced_channel = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.announced_channel = val; } /// When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty /// supports it, they will then enforce the mutual-close output to us matches what we provided @@ -619,7 +637,7 @@ pub extern "C" fn ChannelConfig_set_announced_channel(this_ptr: &mut ChannelConf /// Default value: true. #[no_mangle] pub extern "C" fn ChannelConfig_get_commit_upfront_shutdown_pubkey(this_ptr: &ChannelConfig) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.commit_upfront_shutdown_pubkey; + let mut inner_val = &mut this_ptr.get_native_mut_ref().commit_upfront_shutdown_pubkey; *inner_val } /// When set, we commit to an upfront shutdown_pubkey at channel open. If our counterparty @@ -635,7 +653,7 @@ pub extern "C" fn ChannelConfig_get_commit_upfront_shutdown_pubkey(this_ptr: &Ch /// Default value: true. #[no_mangle] pub extern "C" fn ChannelConfig_set_commit_upfront_shutdown_pubkey(this_ptr: &mut ChannelConfig, mut val: bool) { - unsafe { &mut *this_ptr.inner }.commit_upfront_shutdown_pubkey = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commit_upfront_shutdown_pubkey = val; } /// Limit our total exposure to in-flight HTLCs which are burned to fees as they are too /// small to claim on-chain. @@ -654,7 +672,7 @@ pub extern "C" fn ChannelConfig_set_commit_upfront_shutdown_pubkey(this_ptr: &mu /// Default value: 5_000_000 msat. #[no_mangle] pub extern "C" fn ChannelConfig_get_max_dust_htlc_exposure_msat(this_ptr: &ChannelConfig) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.max_dust_htlc_exposure_msat; + let mut inner_val = &mut this_ptr.get_native_mut_ref().max_dust_htlc_exposure_msat; *inner_val } /// Limit our total exposure to in-flight HTLCs which are burned to fees as they are too @@ -674,7 +692,7 @@ pub extern "C" fn ChannelConfig_get_max_dust_htlc_exposure_msat(this_ptr: &Chann /// Default value: 5_000_000 msat. #[no_mangle] pub extern "C" fn ChannelConfig_set_max_dust_htlc_exposure_msat(this_ptr: &mut ChannelConfig, mut val: u64) { - unsafe { &mut *this_ptr.inner }.max_dust_htlc_exposure_msat = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.max_dust_htlc_exposure_msat = val; } /// The additional fee we're willing to pay to avoid waiting for the counterparty's /// `to_self_delay` to reclaim funds. @@ -700,7 +718,7 @@ pub extern "C" fn ChannelConfig_set_max_dust_htlc_exposure_msat(this_ptr: &mut C /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background #[no_mangle] pub extern "C" fn ChannelConfig_get_force_close_avoidance_max_fee_satoshis(this_ptr: &ChannelConfig) -> u64 { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.force_close_avoidance_max_fee_satoshis; + let mut inner_val = &mut this_ptr.get_native_mut_ref().force_close_avoidance_max_fee_satoshis; *inner_val } /// The additional fee we're willing to pay to avoid waiting for the counterparty's @@ -727,13 +745,13 @@ pub extern "C" fn ChannelConfig_get_force_close_avoidance_max_fee_satoshis(this_ /// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background #[no_mangle] pub extern "C" fn ChannelConfig_set_force_close_avoidance_max_fee_satoshis(this_ptr: &mut ChannelConfig, mut val: u64) { - unsafe { &mut *this_ptr.inner }.force_close_avoidance_max_fee_satoshis = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.force_close_avoidance_max_fee_satoshis = val; } /// Constructs a new ChannelConfig given each field #[must_use] #[no_mangle] pub extern "C" fn ChannelConfig_new(mut forwarding_fee_proportional_millionths_arg: u32, mut forwarding_fee_base_msat_arg: u32, mut cltv_expiry_delta_arg: u16, mut announced_channel_arg: bool, mut commit_upfront_shutdown_pubkey_arg: bool, mut max_dust_htlc_exposure_msat_arg: u64, mut force_close_avoidance_max_fee_satoshis_arg: u64) -> ChannelConfig { - ChannelConfig { inner: Box::into_raw(Box::new(nativeChannelConfig { + ChannelConfig { inner: ObjOps::heap_alloc(nativeChannelConfig { forwarding_fee_proportional_millionths: forwarding_fee_proportional_millionths_arg, forwarding_fee_base_msat: forwarding_fee_base_msat_arg, cltv_expiry_delta: cltv_expiry_delta_arg, @@ -741,13 +759,13 @@ pub extern "C" fn ChannelConfig_new(mut forwarding_fee_proportional_millionths_a commit_upfront_shutdown_pubkey: commit_upfront_shutdown_pubkey_arg, max_dust_htlc_exposure_msat: max_dust_htlc_exposure_msat_arg, force_close_avoidance_max_fee_satoshis: force_close_avoidance_max_fee_satoshis_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for ChannelConfig { fn clone(&self) -> Self { Self { inner: if <*mut nativeChannelConfig>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -766,12 +784,12 @@ pub extern "C" fn ChannelConfig_clone(orig: &ChannelConfig) -> ChannelConfig { #[must_use] #[no_mangle] pub extern "C" fn ChannelConfig_default() -> ChannelConfig { - ChannelConfig { inner: Box::into_raw(Box::new(Default::default())), is_owned: true } + ChannelConfig { inner: ObjOps::heap_alloc(Default::default()), is_owned: true } } #[no_mangle] /// Serialize the ChannelConfig object into a byte array which can be read by ChannelConfig_read pub extern "C" fn ChannelConfig_write(obj: &ChannelConfig) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner }) + crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] pub(crate) extern "C" fn ChannelConfig_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { @@ -781,7 +799,7 @@ pub(crate) extern "C" fn ChannelConfig_write_void(obj: *const c_void) -> crate:: /// Read a ChannelConfig from a byte array, created by ChannelConfig_write pub extern "C" fn ChannelConfig_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelConfigDecodeErrorZ { let res = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::config::ChannelConfig { inner: Box::into_raw(Box::new(o)), is_owned: true } }).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 mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::config::ChannelConfig { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_res } @@ -810,7 +828,7 @@ pub struct UserConfig { impl Drop for UserConfig { fn drop(&mut self) { if self.is_owned && !<*mut nativeUserConfig>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -823,11 +841,17 @@ extern "C" fn UserConfig_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeUserConfig); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl UserConfig { + pub(crate) fn get_native_ref(&self) -> &'static nativeUserConfig { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUserConfig { + 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 nativeUserConfig { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -835,35 +859,35 @@ impl UserConfig { /// Channel config that we propose to our counterparty. #[no_mangle] pub extern "C" fn UserConfig_get_own_channel_config(this_ptr: &UserConfig) -> crate::lightning::util::config::ChannelHandshakeConfig { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.own_channel_config; - crate::lightning::util::config::ChannelHandshakeConfig { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().own_channel_config; + crate::lightning::util::config::ChannelHandshakeConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Channel config that we propose to our counterparty. #[no_mangle] pub extern "C" fn UserConfig_set_own_channel_config(this_ptr: &mut UserConfig, mut val: crate::lightning::util::config::ChannelHandshakeConfig) { - unsafe { &mut *this_ptr.inner }.own_channel_config = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.own_channel_config = *unsafe { Box::from_raw(val.take_inner()) }; } /// Limits applied to our counterparty's proposed channel config settings. #[no_mangle] pub extern "C" fn UserConfig_get_peer_channel_config_limits(this_ptr: &UserConfig) -> crate::lightning::util::config::ChannelHandshakeLimits { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.peer_channel_config_limits; - crate::lightning::util::config::ChannelHandshakeLimits { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().peer_channel_config_limits; + crate::lightning::util::config::ChannelHandshakeLimits { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Limits applied to our counterparty's proposed channel config settings. #[no_mangle] pub extern "C" fn UserConfig_set_peer_channel_config_limits(this_ptr: &mut UserConfig, mut val: crate::lightning::util::config::ChannelHandshakeLimits) { - unsafe { &mut *this_ptr.inner }.peer_channel_config_limits = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.peer_channel_config_limits = *unsafe { Box::from_raw(val.take_inner()) }; } /// Channel config which affects behavior during channel lifetime. #[no_mangle] pub extern "C" fn UserConfig_get_channel_options(this_ptr: &UserConfig) -> crate::lightning::util::config::ChannelConfig { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_options; - crate::lightning::util::config::ChannelConfig { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_options; + crate::lightning::util::config::ChannelConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// Channel config which affects behavior during channel lifetime. #[no_mangle] pub extern "C" fn UserConfig_set_channel_options(this_ptr: &mut UserConfig, mut val: crate::lightning::util::config::ChannelConfig) { - unsafe { &mut *this_ptr.inner }.channel_options = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_options = *unsafe { Box::from_raw(val.take_inner()) }; } /// If this is set to false, we will reject any HTLCs which were to be forwarded over private /// channels. This prevents us from taking on HTLC-forwarding risk when we intend to run as a @@ -883,7 +907,7 @@ pub extern "C" fn UserConfig_set_channel_options(this_ptr: &mut UserConfig, mut /// Default value: false. #[no_mangle] pub extern "C" fn UserConfig_get_accept_forwards_to_priv_channels(this_ptr: &UserConfig) -> bool { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.accept_forwards_to_priv_channels; + let mut inner_val = &mut this_ptr.get_native_mut_ref().accept_forwards_to_priv_channels; *inner_val } /// If this is set to false, we will reject any HTLCs which were to be forwarded over private @@ -904,24 +928,24 @@ pub extern "C" fn UserConfig_get_accept_forwards_to_priv_channels(this_ptr: &Use /// Default value: false. #[no_mangle] pub extern "C" fn UserConfig_set_accept_forwards_to_priv_channels(this_ptr: &mut UserConfig, mut val: bool) { - unsafe { &mut *this_ptr.inner }.accept_forwards_to_priv_channels = val; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.accept_forwards_to_priv_channels = val; } /// Constructs a new UserConfig given each field #[must_use] #[no_mangle] pub extern "C" fn UserConfig_new(mut own_channel_config_arg: crate::lightning::util::config::ChannelHandshakeConfig, mut peer_channel_config_limits_arg: crate::lightning::util::config::ChannelHandshakeLimits, mut channel_options_arg: crate::lightning::util::config::ChannelConfig, mut accept_forwards_to_priv_channels_arg: bool) -> UserConfig { - UserConfig { inner: Box::into_raw(Box::new(nativeUserConfig { + UserConfig { inner: ObjOps::heap_alloc(nativeUserConfig { own_channel_config: *unsafe { Box::from_raw(own_channel_config_arg.take_inner()) }, peer_channel_config_limits: *unsafe { Box::from_raw(peer_channel_config_limits_arg.take_inner()) }, channel_options: *unsafe { Box::from_raw(channel_options_arg.take_inner()) }, accept_forwards_to_priv_channels: accept_forwards_to_priv_channels_arg, - })), is_owned: true } + }), is_owned: true } } impl Clone for UserConfig { fn clone(&self) -> Self { Self { inner: if <*mut nativeUserConfig>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -940,5 +964,5 @@ pub extern "C" fn UserConfig_clone(orig: &UserConfig) -> UserConfig { #[must_use] #[no_mangle] pub extern "C" fn UserConfig_default() -> UserConfig { - UserConfig { inner: Box::into_raw(Box::new(Default::default())), is_owned: true } + UserConfig { inner: ObjOps::heap_alloc(Default::default()), is_owned: true } } diff --git a/lightning-c-bindings/src/lightning/util/errors.rs b/lightning-c-bindings/src/lightning/util/errors.rs index 8f04326..4764a70 100644 --- a/lightning-c-bindings/src/lightning/util/errors.rs +++ b/lightning-c-bindings/src/lightning/util/errors.rs @@ -168,7 +168,7 @@ impl APIError { nativeAPIError::IncompatibleShutdownScript {ref script, } => { let mut script_nonref = (*script).clone(); APIError::IncompatibleShutdownScript { - script: crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(script_nonref)), is_owned: true }, + script: crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(script_nonref), is_owned: true }, } }, } @@ -200,7 +200,7 @@ impl APIError { nativeAPIError::MonitorUpdateFailed => APIError::MonitorUpdateFailed, nativeAPIError::IncompatibleShutdownScript {mut script, } => { APIError::IncompatibleShutdownScript { - script: crate::lightning::ln::script::ShutdownScript { inner: Box::into_raw(Box::new(script)), is_owned: true }, + script: crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(script), is_owned: true }, } }, } diff --git a/lightning-c-bindings/src/lightning/util/events.rs b/lightning-c-bindings/src/lightning/util/events.rs index 491812d..611670f 100644 --- a/lightning-c-bindings/src/lightning/util/events.rs +++ b/lightning-c-bindings/src/lightning/util/events.rs @@ -1013,7 +1013,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendAcceptChannel { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::AcceptChannel { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::AcceptChannel { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendOpenChannel {ref node_id, ref msg, } => { @@ -1021,7 +1021,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendOpenChannel { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::OpenChannel { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::OpenChannel { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendFundingCreated {ref node_id, ref msg, } => { @@ -1029,7 +1029,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendFundingCreated { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::FundingCreated { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingCreated { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendFundingSigned {ref node_id, ref msg, } => { @@ -1037,7 +1037,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendFundingSigned { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::FundingSigned { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingSigned { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendFundingLocked {ref node_id, ref msg, } => { @@ -1045,7 +1045,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendFundingLocked { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::FundingLocked { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingLocked { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendAnnouncementSignatures {ref node_id, ref msg, } => { @@ -1053,7 +1053,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendAnnouncementSignatures { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::AnnouncementSignatures { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::AnnouncementSignatures { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::UpdateHTLCs {ref node_id, ref updates, } => { @@ -1061,7 +1061,7 @@ impl MessageSendEvent { let mut updates_nonref = (*updates).clone(); MessageSendEvent::UpdateHTLCs { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - updates: crate::lightning::ln::msgs::CommitmentUpdate { inner: Box::into_raw(Box::new(updates_nonref)), is_owned: true }, + updates: crate::lightning::ln::msgs::CommitmentUpdate { inner: ObjOps::heap_alloc(updates_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendRevokeAndACK {ref node_id, ref msg, } => { @@ -1069,7 +1069,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendRevokeAndACK { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::RevokeAndACK { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::RevokeAndACK { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendClosingSigned {ref node_id, ref msg, } => { @@ -1077,7 +1077,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendClosingSigned { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::ClosingSigned { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ClosingSigned { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendShutdown {ref node_id, ref msg, } => { @@ -1085,7 +1085,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendShutdown { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::Shutdown { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::Shutdown { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendChannelReestablish {ref node_id, ref msg, } => { @@ -1093,27 +1093,27 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendChannelReestablish { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::ChannelReestablish { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelReestablish { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::BroadcastChannelAnnouncement {ref msg, ref update_msg, } => { let mut msg_nonref = (*msg).clone(); let mut update_msg_nonref = (*update_msg).clone(); MessageSendEvent::BroadcastChannelAnnouncement { - msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, - update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(update_msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, + update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(update_msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::BroadcastNodeAnnouncement {ref msg, } => { let mut msg_nonref = (*msg).clone(); MessageSendEvent::BroadcastNodeAnnouncement { - msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::BroadcastChannelUpdate {ref msg, } => { let mut msg_nonref = (*msg).clone(); MessageSendEvent::BroadcastChannelUpdate { - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendChannelUpdate {ref node_id, ref msg, } => { @@ -1121,7 +1121,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendChannelUpdate { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::HandleError {ref node_id, ref action, } => { @@ -1143,7 +1143,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendChannelRangeQuery { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::QueryChannelRange { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendShortIdsQuery {ref node_id, ref msg, } => { @@ -1151,7 +1151,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendShortIdsQuery { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::QueryShortChannelIds { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, nativeMessageSendEvent::SendReplyChannelRange {ref node_id, ref msg, } => { @@ -1159,7 +1159,7 @@ impl MessageSendEvent { let mut msg_nonref = (*msg).clone(); MessageSendEvent::SendReplyChannelRange { node_id: crate::c_types::PublicKey::from_rust(&node_id_nonref), - msg: crate::lightning::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(msg_nonref)), is_owned: true }, + msg: crate::lightning::ln::msgs::ReplyChannelRange { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, } @@ -1170,89 +1170,89 @@ impl MessageSendEvent { nativeMessageSendEvent::SendAcceptChannel {mut node_id, mut msg, } => { MessageSendEvent::SendAcceptChannel { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::AcceptChannel { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::AcceptChannel { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendOpenChannel {mut node_id, mut msg, } => { MessageSendEvent::SendOpenChannel { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::OpenChannel { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::OpenChannel { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendFundingCreated {mut node_id, mut msg, } => { MessageSendEvent::SendFundingCreated { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::FundingCreated { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingCreated { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendFundingSigned {mut node_id, mut msg, } => { MessageSendEvent::SendFundingSigned { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::FundingSigned { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingSigned { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendFundingLocked {mut node_id, mut msg, } => { MessageSendEvent::SendFundingLocked { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::FundingLocked { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::FundingLocked { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendAnnouncementSignatures {mut node_id, mut msg, } => { MessageSendEvent::SendAnnouncementSignatures { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::AnnouncementSignatures { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::AnnouncementSignatures { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::UpdateHTLCs {mut node_id, mut updates, } => { MessageSendEvent::UpdateHTLCs { node_id: crate::c_types::PublicKey::from_rust(&node_id), - updates: crate::lightning::ln::msgs::CommitmentUpdate { inner: Box::into_raw(Box::new(updates)), is_owned: true }, + updates: crate::lightning::ln::msgs::CommitmentUpdate { inner: ObjOps::heap_alloc(updates), is_owned: true }, } }, nativeMessageSendEvent::SendRevokeAndACK {mut node_id, mut msg, } => { MessageSendEvent::SendRevokeAndACK { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::RevokeAndACK { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::RevokeAndACK { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendClosingSigned {mut node_id, mut msg, } => { MessageSendEvent::SendClosingSigned { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::ClosingSigned { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ClosingSigned { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendShutdown {mut node_id, mut msg, } => { MessageSendEvent::SendShutdown { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::Shutdown { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::Shutdown { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendChannelReestablish {mut node_id, mut msg, } => { MessageSendEvent::SendChannelReestablish { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::ChannelReestablish { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelReestablish { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::BroadcastChannelAnnouncement {mut msg, mut update_msg, } => { MessageSendEvent::BroadcastChannelAnnouncement { - msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: Box::into_raw(Box::new(msg)), is_owned: true }, - update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(update_msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(msg), is_owned: true }, + update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(update_msg), is_owned: true }, } }, nativeMessageSendEvent::BroadcastNodeAnnouncement {mut msg, } => { MessageSendEvent::BroadcastNodeAnnouncement { - msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::BroadcastChannelUpdate {mut msg, } => { MessageSendEvent::BroadcastChannelUpdate { - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendChannelUpdate {mut node_id, mut msg, } => { MessageSendEvent::SendChannelUpdate { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::ChannelUpdate { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::HandleError {mut node_id, mut action, } => { @@ -1269,19 +1269,19 @@ impl MessageSendEvent { nativeMessageSendEvent::SendChannelRangeQuery {mut node_id, mut msg, } => { MessageSendEvent::SendChannelRangeQuery { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::QueryChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::QueryChannelRange { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendShortIdsQuery {mut node_id, mut msg, } => { MessageSendEvent::SendShortIdsQuery { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::QueryShortChannelIds { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::QueryShortChannelIds { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, nativeMessageSendEvent::SendReplyChannelRange {mut node_id, mut msg, } => { MessageSendEvent::SendReplyChannelRange { node_id: crate::c_types::PublicKey::from_rust(&node_id), - msg: crate::lightning::ln::msgs::ReplyChannelRange { inner: Box::into_raw(Box::new(msg)), is_owned: true }, + msg: crate::lightning::ln::msgs::ReplyChannelRange { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, } diff --git a/lightning-c-bindings/src/lightning_background_processor.rs b/lightning-c-bindings/src/lightning_background_processor.rs index fc44da9..5279e3a 100644 --- a/lightning-c-bindings/src/lightning_background_processor.rs +++ b/lightning-c-bindings/src/lightning_background_processor.rs @@ -52,7 +52,7 @@ pub struct BackgroundProcessor { impl Drop for BackgroundProcessor { fn drop(&mut self) { if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -65,11 +65,17 @@ extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBackgroundProcessor); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl BackgroundProcessor { + pub(crate) fn get_native_ref(&self) -> &'static nativeBackgroundProcessor { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBackgroundProcessor { + 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 nativeBackgroundProcessor { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -106,7 +112,7 @@ pub(crate) extern "C" fn ChannelManagerPersister_clone_fields(orig: &ChannelMana use lightning_background_processor::ChannelManagerPersister as rustChannelManagerPersister; impl rustChannelManagerPersister for ChannelManagerPersister { fn persist_manager(&self, mut channel_manager: &lightning::ln::channelmanager::ChannelManager) -> Result<(), std::io::Error> { - let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { (channel_manager as *const _) as *mut _ }, is_owned: false }); + let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_manager as *const _) as *mut _) }, is_owned: false }); 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(<*mut _>::take_ptr(&mut ret.contents.err)) }).to_rust() })}; local_ret } @@ -155,8 +161,8 @@ impl Drop for ChannelManagerPersister { #[must_use] #[no_mangle] pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning_background_processor::ChannelManagerPersister, mut event_handler: crate::lightning::util::events::EventHandler, chain_monitor: &crate::lightning::chain::chainmonitor::ChainMonitor, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager, peer_manager: &crate::lightning::ln::peer_handler::PeerManager, mut logger: crate::lightning::util::logger::Logger) -> BackgroundProcessor { - let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, unsafe { &*chain_monitor.inner }, unsafe { &*channel_manager.inner }, unsafe { &*peer_manager.inner }, logger); - BackgroundProcessor { inner: Box::into_raw(Box::new(ret)), is_owned: true } + let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, chain_monitor.get_native_ref(), channel_manager.get_native_ref(), peer_manager.get_native_ref(), logger); + BackgroundProcessor { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting diff --git a/lightning-c-bindings/src/lightning_invoice/mod.rs b/lightning-c-bindings/src/lightning_invoice/mod.rs index 7ab1c2e..80b6d5d 100644 --- a/lightning-c-bindings/src/lightning_invoice/mod.rs +++ b/lightning-c-bindings/src/lightning_invoice/mod.rs @@ -55,7 +55,7 @@ pub extern "C" fn Invoice_from_str(s: crate::c_types::Str) -> crate::c_types::de match lightning_invoice::Invoice::from_str(s.into_str()) { Ok(r) => { crate::c_types::CResultTempl::ok( - crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(r), is_owned: true } ) }, Err(e) => crate::c_types::CResultTempl::err(()), @@ -67,7 +67,7 @@ pub extern "C" fn SignedRawInvoice_from_str(s: crate::c_types::Str) -> crate::c_ match lightning_invoice::SignedRawInvoice::from_str(s.into_str()) { Ok(r) => { crate::c_types::CResultTempl::ok( - crate::lightning_invoice::SignedRawInvoice { inner: Box::into_raw(Box::new(r)), is_owned: true } + crate::lightning_invoice::SignedRawInvoice { inner: ObjOps::heap_alloc(r), is_owned: true } ) }, Err(e) => crate::c_types::CResultTempl::err(()), @@ -84,12 +84,12 @@ use crate::c_types::*; #[no_mangle] /// Get the string representation of a Invoice object pub extern "C" fn Invoice_to_str(o: &crate::lightning_invoice::Invoice) -> Str { - format!("{}", unsafe { &*o.inner }).into() + format!("{}", o.get_native_ref()).into() } #[no_mangle] /// Get the string representation of a SignedRawInvoice object pub extern "C" fn SignedRawInvoice_to_str(o: &crate::lightning_invoice::SignedRawInvoice) -> Str { - format!("{}", unsafe { &*o.inner }).into() + format!("{}", o.get_native_ref()).into() } #[no_mangle] /// Get the string representation of a Currency object @@ -172,7 +172,7 @@ pub struct Invoice { impl Drop for Invoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -185,11 +185,17 @@ extern "C" fn Invoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Invoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoice { + 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 nativeInvoice { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -201,13 +207,13 @@ impl Invoice { pub extern "C" fn Invoice_eq(a: &Invoice, b: &Invoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for Invoice { fn clone(&self) -> Self { Self { inner: if <*mut nativeInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -249,7 +255,7 @@ pub struct SignedRawInvoice { impl Drop for SignedRawInvoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeSignedRawInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -262,11 +268,17 @@ extern "C" fn SignedRawInvoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeSignedRawInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl SignedRawInvoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeSignedRawInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeSignedRawInvoice { + 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 nativeSignedRawInvoice { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -278,13 +290,13 @@ impl SignedRawInvoice { pub extern "C" fn SignedRawInvoice_eq(a: &SignedRawInvoice, b: &SignedRawInvoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for SignedRawInvoice { fn clone(&self) -> Self { Self { inner: if <*mut nativeSignedRawInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -326,7 +338,7 @@ pub struct RawInvoice { impl Drop for RawInvoice { fn drop(&mut self) { if self.is_owned && !<*mut nativeRawInvoice>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -339,11 +351,17 @@ extern "C" fn RawInvoice_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRawInvoice); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RawInvoice { + pub(crate) fn get_native_ref(&self) -> &'static nativeRawInvoice { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRawInvoice { + 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 nativeRawInvoice { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -351,13 +369,13 @@ impl RawInvoice { /// data part #[no_mangle] pub extern "C" fn RawInvoice_get_data(this_ptr: &RawInvoice) -> crate::lightning_invoice::RawDataPart { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.data; - crate::lightning_invoice::RawDataPart { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().data; + crate::lightning_invoice::RawDataPart { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// data part #[no_mangle] pub extern "C" fn RawInvoice_set_data(this_ptr: &mut RawInvoice, mut val: crate::lightning_invoice::RawDataPart) { - unsafe { &mut *this_ptr.inner }.data = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.data = *unsafe { Box::from_raw(val.take_inner()) }; } /// Checks if two RawInvoices contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -366,13 +384,13 @@ pub extern "C" fn RawInvoice_set_data(this_ptr: &mut RawInvoice, mut val: crate: pub extern "C" fn RawInvoice_eq(a: &RawInvoice, b: &RawInvoice) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RawInvoice { fn clone(&self) -> Self { Self { inner: if <*mut nativeRawInvoice>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -410,7 +428,7 @@ pub struct RawDataPart { impl Drop for RawDataPart { fn drop(&mut self) { if self.is_owned && !<*mut nativeRawDataPart>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -423,11 +441,17 @@ extern "C" fn RawDataPart_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeRawDataPart); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl RawDataPart { + pub(crate) fn get_native_ref(&self) -> &'static nativeRawDataPart { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeRawDataPart { + 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 nativeRawDataPart { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -435,13 +459,13 @@ impl RawDataPart { /// generation time of the invoice #[no_mangle] pub extern "C" fn RawDataPart_get_timestamp(this_ptr: &RawDataPart) -> crate::lightning_invoice::PositiveTimestamp { - let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.timestamp; - crate::lightning_invoice::PositiveTimestamp { inner: unsafe { ( (&(*inner_val) as *const _) as *mut _) }, is_owned: false } + let mut inner_val = &mut this_ptr.get_native_mut_ref().timestamp; + crate::lightning_invoice::PositiveTimestamp { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const _) as *mut _) }, is_owned: false } } /// generation time of the invoice #[no_mangle] pub extern "C" fn RawDataPart_set_timestamp(this_ptr: &mut RawDataPart, mut val: crate::lightning_invoice::PositiveTimestamp) { - unsafe { &mut *this_ptr.inner }.timestamp = *unsafe { Box::from_raw(val.take_inner()) }; + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp = *unsafe { Box::from_raw(val.take_inner()) }; } /// Checks if two RawDataParts contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. @@ -450,13 +474,13 @@ pub extern "C" fn RawDataPart_set_timestamp(this_ptr: &mut RawDataPart, mut val: pub extern "C" fn RawDataPart_eq(a: &RawDataPart, b: &RawDataPart) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for RawDataPart { fn clone(&self) -> Self { Self { inner: if <*mut nativeRawDataPart>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -499,7 +523,7 @@ pub struct PositiveTimestamp { impl Drop for PositiveTimestamp { fn drop(&mut self) { if self.is_owned && !<*mut nativePositiveTimestamp>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -512,11 +536,17 @@ extern "C" fn PositiveTimestamp_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePositiveTimestamp); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PositiveTimestamp { + pub(crate) fn get_native_ref(&self) -> &'static nativePositiveTimestamp { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePositiveTimestamp { + 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 nativePositiveTimestamp { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -528,13 +558,13 @@ impl PositiveTimestamp { pub extern "C" fn PositiveTimestamp_eq(a: &PositiveTimestamp, b: &PositiveTimestamp) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for PositiveTimestamp { fn clone(&self) -> Self { Self { inner: if <*mut nativePositiveTimestamp>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -751,7 +781,7 @@ pub struct Sha256 { impl Drop for Sha256 { fn drop(&mut self) { if self.is_owned && !<*mut nativeSha256>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -764,11 +794,17 @@ extern "C" fn Sha256_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeSha256); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Sha256 { + pub(crate) fn get_native_ref(&self) -> &'static nativeSha256 { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeSha256 { + 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 nativeSha256 { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -780,13 +816,13 @@ impl Sha256 { pub extern "C" fn Sha256_eq(a: &Sha256, b: &Sha256) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for Sha256 { fn clone(&self) -> Self { Self { inner: if <*mut nativeSha256>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -827,7 +863,7 @@ pub struct Description { impl Drop for Description { fn drop(&mut self) { if self.is_owned && !<*mut nativeDescription>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -840,11 +876,17 @@ extern "C" fn Description_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeDescription); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl Description { + pub(crate) fn get_native_ref(&self) -> &'static nativeDescription { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeDescription { + 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 nativeDescription { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -856,13 +898,13 @@ impl Description { pub extern "C" fn Description_eq(a: &Description, b: &Description) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for Description { fn clone(&self) -> Self { Self { inner: if <*mut nativeDescription>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -900,7 +942,7 @@ pub struct PayeePubKey { impl Drop for PayeePubKey { fn drop(&mut self) { if self.is_owned && !<*mut nativePayeePubKey>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -913,11 +955,17 @@ extern "C" fn PayeePubKey_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePayeePubKey); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PayeePubKey { + pub(crate) fn get_native_ref(&self) -> &'static nativePayeePubKey { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePayeePubKey { + 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 nativePayeePubKey { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -929,13 +977,13 @@ impl PayeePubKey { pub extern "C" fn PayeePubKey_eq(a: &PayeePubKey, b: &PayeePubKey) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for PayeePubKey { fn clone(&self) -> Self { Self { inner: if <*mut nativePayeePubKey>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -979,7 +1027,7 @@ pub struct ExpiryTime { impl Drop for ExpiryTime { fn drop(&mut self) { if self.is_owned && !<*mut nativeExpiryTime>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -992,11 +1040,17 @@ extern "C" fn ExpiryTime_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeExpiryTime); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl ExpiryTime { + pub(crate) fn get_native_ref(&self) -> &'static nativeExpiryTime { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeExpiryTime { + 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 nativeExpiryTime { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1008,13 +1062,13 @@ impl ExpiryTime { pub extern "C" fn ExpiryTime_eq(a: &ExpiryTime, b: &ExpiryTime) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for ExpiryTime { fn clone(&self) -> Self { Self { inner: if <*mut nativeExpiryTime>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1052,7 +1106,7 @@ pub struct MinFinalCltvExpiry { impl Drop for MinFinalCltvExpiry { fn drop(&mut self) { if self.is_owned && !<*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1065,11 +1119,17 @@ extern "C" fn MinFinalCltvExpiry_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMinFinalCltvExpiry); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl MinFinalCltvExpiry { + pub(crate) fn get_native_ref(&self) -> &'static nativeMinFinalCltvExpiry { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMinFinalCltvExpiry { + 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 nativeMinFinalCltvExpiry { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1081,13 +1141,13 @@ impl MinFinalCltvExpiry { pub extern "C" fn MinFinalCltvExpiry_eq(a: &MinFinalCltvExpiry, b: &MinFinalCltvExpiry) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for MinFinalCltvExpiry { fn clone(&self) -> Self { Self { inner: if <*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1268,7 +1328,7 @@ pub struct InvoiceSignature { impl Drop for InvoiceSignature { fn drop(&mut self) { if self.is_owned && !<*mut nativeInvoiceSignature>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1281,11 +1341,17 @@ extern "C" fn InvoiceSignature_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeInvoiceSignature); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl InvoiceSignature { + pub(crate) fn get_native_ref(&self) -> &'static nativeInvoiceSignature { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoiceSignature { + 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 nativeInvoiceSignature { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1297,13 +1363,13 @@ impl InvoiceSignature { pub extern "C" fn InvoiceSignature_eq(a: &InvoiceSignature, b: &InvoiceSignature) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for InvoiceSignature { fn clone(&self) -> Self { Self { inner: if <*mut nativeInvoiceSignature>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1345,7 +1411,7 @@ pub struct PrivateRoute { impl Drop for PrivateRoute { fn drop(&mut self) { if self.is_owned && !<*mut nativePrivateRoute>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -1358,11 +1424,17 @@ extern "C" fn PrivateRoute_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativePrivateRoute); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl PrivateRoute { + pub(crate) fn get_native_ref(&self) -> &'static nativePrivateRoute { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePrivateRoute { + 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 nativePrivateRoute { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -1374,13 +1446,13 @@ impl PrivateRoute { pub extern "C" fn PrivateRoute_eq(a: &PrivateRoute, b: &PrivateRoute) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } - if unsafe { &*a.inner } == unsafe { &*b.inner } { true } else { false } + if a.get_native_ref() == b.get_native_ref() { true } else { false } } impl Clone for PrivateRoute { fn clone(&self) -> Self { Self { inner: if <*mut nativePrivateRoute>::is_null(self.inner) { std::ptr::null_mut() } else { - Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) }, + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } } @@ -1403,7 +1475,7 @@ pub extern "C" fn PrivateRoute_clone(orig: &PrivateRoute) -> PrivateRoute { #[no_mangle] pub extern "C" fn SignedRawInvoice_into_parts(mut this_arg: SignedRawInvoice) -> crate::c_types::derived::C3Tuple_RawInvoice_u832InvoiceSignatureZ { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_parts(); - let (mut orig_ret_0, mut orig_ret_1, mut orig_ret_2) = ret; let mut local_ret = (crate::lightning_invoice::RawInvoice { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1 }, crate::lightning_invoice::InvoiceSignature { inner: Box::into_raw(Box::new(orig_ret_2)), is_owned: true }).into(); + let (mut orig_ret_0, mut orig_ret_1, mut orig_ret_2) = ret; let mut local_ret = (crate::lightning_invoice::RawInvoice { inner: ObjOps::heap_alloc(orig_ret_0), is_owned: true }, crate::c_types::ThirtyTwoBytes { data: orig_ret_1 }, crate::lightning_invoice::InvoiceSignature { inner: ObjOps::heap_alloc(orig_ret_2), is_owned: true }).into(); local_ret } @@ -1411,15 +1483,15 @@ pub extern "C" fn SignedRawInvoice_into_parts(mut this_arg: SignedRawInvoice) -> #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_raw_invoice(this_arg: &SignedRawInvoice) -> crate::lightning_invoice::RawInvoice { - let mut ret = unsafe { &*this_arg.inner }.raw_invoice(); - crate::lightning_invoice::RawInvoice { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.raw_invoice(); + crate::lightning_invoice::RawInvoice { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// The hash of the `RawInvoice` that was signed. #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_hash(this_arg: &SignedRawInvoice) -> *const [u8; 32] { - let mut ret = unsafe { &*this_arg.inner }.hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.hash(); ret } @@ -1427,16 +1499,16 @@ pub extern "C" fn SignedRawInvoice_hash(this_arg: &SignedRawInvoice) -> *const [ #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_signature(this_arg: &SignedRawInvoice) -> crate::lightning_invoice::InvoiceSignature { - let mut ret = unsafe { &*this_arg.inner }.signature(); - crate::lightning_invoice::InvoiceSignature { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false } + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.signature(); + crate::lightning_invoice::InvoiceSignature { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const _) as *mut _) }, is_owned: false } } /// Recovers the public key used for signing the invoice from the recoverable signature. #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_recover_payee_pub_key(this_arg: &SignedRawInvoice) -> crate::c_types::derived::CResult_PayeePubKeyErrorZ { - let mut ret = unsafe { &*this_arg.inner }.recover_payee_pub_key(); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PayeePubKey { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.recover_payee_pub_key(); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PayeePubKey { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::Secp256k1Error::from_rust(e) }).into() }; local_ret } @@ -1445,7 +1517,7 @@ pub extern "C" fn SignedRawInvoice_recover_payee_pub_key(this_arg: &SignedRawInv #[must_use] #[no_mangle] pub extern "C" fn SignedRawInvoice_check_signature(this_arg: &SignedRawInvoice) -> bool { - let mut ret = unsafe { &*this_arg.inner }.check_signature(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.check_signature(); ret } @@ -1453,7 +1525,7 @@ pub extern "C" fn SignedRawInvoice_check_signature(this_arg: &SignedRawInvoice) #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_hash(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.hash(); crate::c_types::ThirtyTwoBytes { data: ret } } @@ -1462,8 +1534,8 @@ pub extern "C" fn RawInvoice_hash(this_arg: &RawInvoice) -> crate::c_types::Thir #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payment_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 { - let mut ret = unsafe { &*this_arg.inner }.payment_hash(); - let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_hash(); + let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1472,8 +1544,8 @@ pub extern "C" fn RawInvoice_payment_hash(this_arg: &RawInvoice) -> crate::light #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_description(this_arg: &RawInvoice) -> crate::lightning_invoice::Description { - let mut ret = unsafe { &*this_arg.inner }.description(); - let mut local_ret = crate::lightning_invoice::Description { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description(); + let mut local_ret = crate::lightning_invoice::Description { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1482,8 +1554,8 @@ pub extern "C" fn RawInvoice_description(this_arg: &RawInvoice) -> crate::lightn #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payee_pub_key(this_arg: &RawInvoice) -> crate::lightning_invoice::PayeePubKey { - let mut ret = unsafe { &*this_arg.inner }.payee_pub_key(); - let mut local_ret = crate::lightning_invoice::PayeePubKey { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payee_pub_key(); + let mut local_ret = crate::lightning_invoice::PayeePubKey { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1492,8 +1564,8 @@ pub extern "C" fn RawInvoice_payee_pub_key(this_arg: &RawInvoice) -> crate::ligh #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_description_hash(this_arg: &RawInvoice) -> crate::lightning_invoice::Sha256 { - let mut ret = unsafe { &*this_arg.inner }.description_hash(); - let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.description_hash(); + let mut local_ret = crate::lightning_invoice::Sha256 { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1502,8 +1574,8 @@ pub extern "C" fn RawInvoice_description_hash(this_arg: &RawInvoice) -> crate::l #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_expiry_time(this_arg: &RawInvoice) -> crate::lightning_invoice::ExpiryTime { - let mut ret = unsafe { &*this_arg.inner }.expiry_time(); - let mut local_ret = crate::lightning_invoice::ExpiryTime { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expiry_time(); + let mut local_ret = crate::lightning_invoice::ExpiryTime { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1512,8 +1584,8 @@ pub extern "C" fn RawInvoice_expiry_time(this_arg: &RawInvoice) -> crate::lightn #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> crate::lightning_invoice::MinFinalCltvExpiry { - let mut ret = unsafe { &*this_arg.inner }.min_final_cltv_expiry(); - let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiry { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); + let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiry { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1522,7 +1594,7 @@ pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &RawInvoice) -> cra #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_secret(); let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; local_ret } @@ -1532,23 +1604,23 @@ pub extern "C" fn RawInvoice_payment_secret(this_arg: &RawInvoice) -> crate::c_t #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_features(this_arg: &RawInvoice) -> crate::lightning::ln::features::InvoiceFeatures { - let mut ret = unsafe { &*this_arg.inner }.features(); - let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.features(); + let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_private_routes(this_arg: &RawInvoice) -> crate::c_types::derived::CVec_PrivateRouteZ { - let mut ret = unsafe { &*this_arg.inner }.private_routes(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ( (&(*item) as *const _) as *mut _) }, is_owned: false } }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.private_routes(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const _) as *mut _) }, is_owned: false } }); }; local_ret.into() } #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_amount_pico_btc(this_arg: &RawInvoice) -> crate::c_types::derived::COption_u64Z { - let mut ret = unsafe { &*this_arg.inner }.amount_pico_btc(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount_pico_btc(); 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 } @@ -1556,7 +1628,7 @@ pub extern "C" fn RawInvoice_amount_pico_btc(this_arg: &RawInvoice) -> crate::c_ #[must_use] #[no_mangle] pub extern "C" fn RawInvoice_currency(this_arg: &RawInvoice) -> crate::lightning_invoice::Currency { - let mut ret = unsafe { &*this_arg.inner }.currency(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.currency(); crate::lightning_invoice::Currency::native_into(ret) } @@ -1567,7 +1639,7 @@ pub extern "C" fn RawInvoice_currency(this_arg: &RawInvoice) -> crate::lightning #[no_mangle] pub extern "C" fn PositiveTimestamp_from_unix_timestamp(mut unix_seconds: u64) -> crate::c_types::derived::CResult_PositiveTimestampCreationErrorZ { let mut ret = lightning_invoice::PositiveTimestamp::from_unix_timestamp(unix_seconds); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1578,7 +1650,7 @@ pub extern "C" fn PositiveTimestamp_from_unix_timestamp(mut unix_seconds: u64) - #[no_mangle] pub extern "C" fn PositiveTimestamp_from_system_time(mut time: u64) -> crate::c_types::derived::CResult_PositiveTimestampCreationErrorZ { let mut ret = lightning_invoice::PositiveTimestamp::from_system_time((::std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(time))); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PositiveTimestamp { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1586,7 +1658,7 @@ pub extern "C" fn PositiveTimestamp_from_system_time(mut time: u64) -> crate::c_ #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_as_unix_timestamp(this_arg: &PositiveTimestamp) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_unix_timestamp(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_unix_timestamp(); ret } @@ -1594,7 +1666,7 @@ pub extern "C" fn PositiveTimestamp_as_unix_timestamp(this_arg: &PositiveTimesta #[must_use] #[no_mangle] pub extern "C" fn PositiveTimestamp_as_time(this_arg: &PositiveTimestamp) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_time(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_time(); ret.duration_since(::std::time::SystemTime::UNIX_EPOCH).expect("Times must be post-1970").as_secs() } @@ -1603,14 +1675,14 @@ pub extern "C" fn PositiveTimestamp_as_time(this_arg: &PositiveTimestamp) -> u64 #[no_mangle] pub extern "C" fn Invoice_into_signed_raw(mut this_arg: Invoice) -> crate::lightning_invoice::SignedRawInvoice { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_signed_raw(); - crate::lightning_invoice::SignedRawInvoice { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning_invoice::SignedRawInvoice { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Check that the invoice is signed correctly and that key recovery works #[must_use] #[no_mangle] pub extern "C" fn Invoice_check_signature(this_arg: &Invoice) -> crate::c_types::derived::CResult_NoneSemanticErrorZ { - let mut ret = unsafe { &*this_arg.inner }.check_signature(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.check_signature(); 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_invoice::SemanticError::native_into(e) }).into() }; local_ret } @@ -1632,7 +1704,7 @@ pub extern "C" fn Invoice_check_signature(this_arg: &Invoice) -> crate::c_types: #[no_mangle] pub extern "C" fn Invoice_from_signed(mut signed_invoice: crate::lightning_invoice::SignedRawInvoice) -> crate::c_types::derived::CResult_InvoiceSemanticErrorZ { let mut ret = lightning_invoice::Invoice::from_signed(*unsafe { Box::from_raw(signed_invoice.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SemanticError::native_into(e) }).into() }; local_ret } @@ -1640,7 +1712,7 @@ pub extern "C" fn Invoice_from_signed(mut signed_invoice: crate::lightning_invoi #[must_use] #[no_mangle] pub extern "C" fn Invoice_timestamp(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.timestamp(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timestamp(); ret.duration_since(::std::time::SystemTime::UNIX_EPOCH).expect("Times must be post-1970").as_secs() } @@ -1648,7 +1720,7 @@ pub extern "C" fn Invoice_timestamp(this_arg: &Invoice) -> u64 { #[must_use] #[no_mangle] pub extern "C" fn Invoice_payment_hash(this_arg: &Invoice) -> *const [u8; 32] { - let mut ret = unsafe { &*this_arg.inner }.payment_hash(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_hash(); ret.as_inner() } @@ -1658,7 +1730,7 @@ pub extern "C" fn Invoice_payment_hash(this_arg: &Invoice) -> *const [u8; 32] { #[must_use] #[no_mangle] pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.payee_pub_key(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payee_pub_key(); let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } }; local_ret } @@ -1669,7 +1741,7 @@ pub extern "C" fn Invoice_payee_pub_key(this_arg: &Invoice) -> crate::c_types::P #[must_use] #[no_mangle] pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types::ThirtyTwoBytes { - let mut ret = unsafe { &*this_arg.inner }.payment_secret(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.payment_secret(); let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()).0 } } }; local_ret } @@ -1680,8 +1752,8 @@ pub extern "C" fn Invoice_payment_secret(this_arg: &Invoice) -> crate::c_types:: #[must_use] #[no_mangle] pub extern "C" fn Invoice_features(this_arg: &Invoice) -> crate::lightning::ln::features::InvoiceFeatures { - let mut ret = unsafe { &*this_arg.inner }.features(); - let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { { (ret.unwrap()) } } as *const _) as *mut _ }, is_owned: false }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.features(); + let mut local_ret = crate::lightning::ln::features::InvoiceFeatures { inner: unsafe { (if ret.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const _) as *mut _ }, is_owned: false }; local_ret } @@ -1689,7 +1761,7 @@ pub extern "C" fn Invoice_features(this_arg: &Invoice) -> crate::lightning::ln:: #[must_use] #[no_mangle] pub extern "C" fn Invoice_recover_payee_pub_key(this_arg: &Invoice) -> crate::c_types::PublicKey { - let mut ret = unsafe { &*this_arg.inner }.recover_payee_pub_key(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.recover_payee_pub_key(); crate::c_types::PublicKey::from_rust(&ret) } @@ -1697,7 +1769,7 @@ pub extern "C" fn Invoice_recover_payee_pub_key(this_arg: &Invoice) -> crate::c_ #[must_use] #[no_mangle] pub extern "C" fn Invoice_expiry_time(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.expiry_time(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.expiry_time(); ret.as_secs() } @@ -1706,7 +1778,7 @@ pub extern "C" fn Invoice_expiry_time(this_arg: &Invoice) -> u64 { #[must_use] #[no_mangle] pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &Invoice) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.min_final_cltv_expiry(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); ret } @@ -1714,8 +1786,8 @@ pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &Invoice) -> u64 { #[must_use] #[no_mangle] pub extern "C" fn Invoice_private_routes(this_arg: &Invoice) -> crate::c_types::derived::CVec_PrivateRouteZ { - let mut ret = unsafe { &*this_arg.inner }.private_routes(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ( (&(*item) as *const _) as *mut _) }, is_owned: false } }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.private_routes(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning_invoice::PrivateRoute { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const _) as *mut _) }, is_owned: false } }); }; local_ret.into() } @@ -1723,8 +1795,8 @@ pub extern "C" fn Invoice_private_routes(this_arg: &Invoice) -> crate::c_types:: #[must_use] #[no_mangle] pub extern "C" fn Invoice_route_hints(this_arg: &Invoice) -> crate::c_types::derived::CVec_RouteHintZ { - let mut ret = unsafe { &*this_arg.inner }.route_hints(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::routing::router::RouteHint { inner: unsafe { ( (&(*item) as *const _) as *mut _) }, is_owned: false } }); }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.route_hints(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::routing::router::RouteHint { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const _) as *mut _) }, is_owned: false } }); }; local_ret.into() } @@ -1732,7 +1804,7 @@ pub extern "C" fn Invoice_route_hints(this_arg: &Invoice) -> crate::c_types::der #[must_use] #[no_mangle] pub extern "C" fn Invoice_currency(this_arg: &Invoice) -> crate::lightning_invoice::Currency { - let mut ret = unsafe { &*this_arg.inner }.currency(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.currency(); crate::lightning_invoice::Currency::native_into(ret) } @@ -1740,7 +1812,7 @@ pub extern "C" fn Invoice_currency(this_arg: &Invoice) -> crate::lightning_invoi #[must_use] #[no_mangle] pub extern "C" fn Invoice_amount_pico_btc(this_arg: &Invoice) -> crate::c_types::derived::COption_u64Z { - let mut ret = unsafe { &*this_arg.inner }.amount_pico_btc(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.amount_pico_btc(); 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 } @@ -1753,7 +1825,7 @@ pub extern "C" fn Invoice_amount_pico_btc(this_arg: &Invoice) -> crate::c_types: #[no_mangle] pub extern "C" fn Description_new(mut description: crate::c_types::Str) -> crate::c_types::derived::CResult_DescriptionCreationErrorZ { let mut ret = lightning_invoice::Description::new(description.into_string()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Description { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Description { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1772,7 +1844,7 @@ pub extern "C" fn Description_into_inner(mut this_arg: Description) -> crate::c_ #[no_mangle] pub extern "C" fn ExpiryTime_from_seconds(mut seconds: u64) -> crate::c_types::derived::CResult_ExpiryTimeCreationErrorZ { let mut ret = lightning_invoice::ExpiryTime::from_seconds(seconds); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1783,7 +1855,7 @@ pub extern "C" fn ExpiryTime_from_seconds(mut seconds: u64) -> crate::c_types::d #[no_mangle] pub extern "C" fn ExpiryTime_from_duration(mut duration: u64) -> crate::c_types::derived::CResult_ExpiryTimeCreationErrorZ { let mut ret = lightning_invoice::ExpiryTime::from_duration(std::time::Duration::from_secs(duration)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::ExpiryTime { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1791,7 +1863,7 @@ pub extern "C" fn ExpiryTime_from_duration(mut duration: u64) -> crate::c_types: #[must_use] #[no_mangle] pub extern "C" fn ExpiryTime_as_seconds(this_arg: &ExpiryTime) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_seconds(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_seconds(); ret } @@ -1799,7 +1871,7 @@ pub extern "C" fn ExpiryTime_as_seconds(this_arg: &ExpiryTime) -> u64 { #[must_use] #[no_mangle] pub extern "C" fn ExpiryTime_as_duration(this_arg: &ExpiryTime) -> u64 { - let mut ret = unsafe { &*this_arg.inner }.as_duration(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.as_duration(); ret.as_secs() } @@ -1808,7 +1880,7 @@ pub extern "C" fn ExpiryTime_as_duration(this_arg: &ExpiryTime) -> u64 { #[no_mangle] pub extern "C" fn PrivateRoute_new(mut hops: crate::lightning::routing::router::RouteHint) -> crate::c_types::derived::CResult_PrivateRouteCreationErrorZ { let mut ret = lightning_invoice::PrivateRoute::new(*unsafe { Box::from_raw(hops.take_inner()) }); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PrivateRoute { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::PrivateRoute { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::CreationError::native_into(e) }).into() }; local_ret } @@ -1817,7 +1889,7 @@ pub extern "C" fn PrivateRoute_new(mut hops: crate::lightning::routing::router:: #[no_mangle] pub extern "C" fn PrivateRoute_into_inner(mut this_arg: PrivateRoute) -> crate::lightning::routing::router::RouteHint { let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).into_inner(); - crate::lightning::routing::router::RouteHint { inner: Box::into_raw(Box::new(ret)), is_owned: true } + crate::lightning::routing::router::RouteHint { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Errors that may occur when constructing a new `RawInvoice` or `Invoice` diff --git a/lightning-c-bindings/src/lightning_invoice/utils.rs b/lightning-c-bindings/src/lightning_invoice/utils.rs index 6a1fa6c..281da5e 100644 --- a/lightning-c-bindings/src/lightning_invoice/utils.rs +++ b/lightning-c-bindings/src/lightning_invoice/utils.rs @@ -21,8 +21,8 @@ use crate::c_types::*; #[no_mangle] pub extern "C" fn create_invoice_from_channelmanager(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager(unsafe { &*channelmanager.inner }, keys_manager, network.into_native(), local_amt_msat, description.into_string()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager(channelmanager.get_native_ref(), keys_manager, network.into_native(), local_amt_msat, description.into_string()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning_persister.rs b/lightning-c-bindings/src/lightning_persister.rs index 8c4c3fa..bd87bff 100644 --- a/lightning-c-bindings/src/lightning_persister.rs +++ b/lightning-c-bindings/src/lightning_persister.rs @@ -55,7 +55,7 @@ pub struct FilesystemPersister { impl Drop for FilesystemPersister { fn drop(&mut self) { if self.is_owned && !<*mut nativeFilesystemPersister>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } @@ -68,11 +68,17 @@ extern "C" fn FilesystemPersister_free_void(this_ptr: *mut c_void) { unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFilesystemPersister); } } #[allow(unused)] -/// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy impl FilesystemPersister { + pub(crate) fn get_native_ref(&self) -> &'static nativeFilesystemPersister { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFilesystemPersister { + 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 nativeFilesystemPersister { assert!(self.is_owned); - let ret = self.inner; + let ret = ObjOps::untweak_ptr(self.inner); self.inner = std::ptr::null_mut(); ret } @@ -83,14 +89,14 @@ impl FilesystemPersister { #[no_mangle] pub extern "C" fn FilesystemPersister_new(mut path_to_channel_data: crate::c_types::Str) -> FilesystemPersister { let mut ret = lightning_persister::FilesystemPersister::new(path_to_channel_data.into_string()); - FilesystemPersister { inner: Box::into_raw(Box::new(ret)), is_owned: true } + FilesystemPersister { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Get the directory which was provided when this persister was initialized. #[must_use] #[no_mangle] pub extern "C" fn FilesystemPersister_get_data_dir(this_arg: &FilesystemPersister) -> crate::c_types::Str { - let mut ret = unsafe { &*this_arg.inner }.get_data_dir(); + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_data_dir(); ret.into() } @@ -99,7 +105,7 @@ pub extern "C" fn FilesystemPersister_get_data_dir(this_arg: &FilesystemPersiste #[must_use] #[no_mangle] pub extern "C" fn FilesystemPersister_persist_manager(mut data_dir: crate::c_types::Str, manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ { - let mut ret = lightning_persister::FilesystemPersister::persist_manager(data_dir.into_string(), unsafe { &*manager.inner }); + let mut ret = lightning_persister::FilesystemPersister::persist_manager(data_dir.into_string(), manager.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::c_types::IOError::from_rust(e) }).into() }; local_ret } @@ -108,14 +114,14 @@ pub extern "C" fn FilesystemPersister_persist_manager(mut data_dir: crate::c_typ #[must_use] #[no_mangle] pub extern "C" fn FilesystemPersister_read_channelmonitors(this_arg: &FilesystemPersister, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ { - let mut ret = unsafe { &*this_arg.inner }.read_channelmonitors(keys_manager); - 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.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_ret_0_0_1)), is_owned: true }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_channelmonitors(keys_manager); + 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.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_ret_0_0_1), is_owned: true }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() }; local_ret } impl From for crate::lightning::chain::channelmonitor::Persist { fn from(obj: nativeFilesystemPersister) -> Self { - let mut rust_obj = FilesystemPersister { inner: Box::into_raw(Box::new(obj)), is_owned: true }; + let mut rust_obj = FilesystemPersister { inner: ObjOps::heap_alloc(obj), is_owned: true }; let mut ret = FilesystemPersister_as_Persist(&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(); @@ -128,7 +134,7 @@ impl From for crate::lightning::chain::channelmonitor #[no_mangle] pub extern "C" fn FilesystemPersister_as_Persist(this_arg: &FilesystemPersister) -> crate::lightning::chain::channelmonitor::Persist { crate::lightning::chain::channelmonitor::Persist { - 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, persist_new_channel: FilesystemPersister_Persist_persist_new_channel, update_persisted_channel: FilesystemPersister_Persist_update_persisted_channel, @@ -137,13 +143,13 @@ pub extern "C" fn FilesystemPersister_as_Persist(this_arg: &FilesystemPersister) #[must_use] extern "C" fn FilesystemPersister_Persist_persist_new_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, monitor: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { - let mut ret = >::persist_new_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, unsafe { &*monitor.inner }); + let mut ret = >::persist_new_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, monitor.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::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret } #[must_use] extern "C" fn FilesystemPersister_Persist_update_persisted_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, _update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, monitor: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ { - let mut ret = >::update_persisted_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, unsafe { &*_update.inner }, unsafe { &*monitor.inner }); + let mut ret = >::update_persisted_channel(unsafe { &mut *(this_arg as *mut nativeFilesystemPersister) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, _update.get_native_ref(), monitor.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::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() }; local_ret }