X-Git-Url: http://git.bitcoin.ninja/index.cgi?p=ldk-c-bindings;a=blobdiff_plain;f=lightning-c-bindings%2Fsrc%2Flightning%2Fchain%2Fchannelmonitor.rs;h=1484bbf60bacfcb5a57f772f334060568df57df2;hp=11612160ec4b3c78d551a2ab7565a2e002fbf9dc;hb=dd5bf474af6c806b20c26f4f2b751f3226a94dfd;hpb=a82e075188fc15a103234832686915c196bfe240 diff --git a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs index 1161216..1484bbf 100644 --- a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs @@ -21,12 +21,13 @@ use std::str::FromStr; use std::ffi::c_void; +use core::convert::Infallible; use bitcoin::hashes::Hash; use crate::c_types::*; use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport; -type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport; +pub(crate) type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport; /// An update generated by the underlying Channel itself which contains some new information the /// ChannelMonitor should be made aware of. @@ -48,7 +49,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)) }; } } } @@ -57,15 +58,21 @@ impl Drop for ChannelMonitorUpdate { pub extern "C" fn ChannelMonitorUpdate_free(this_obj: ChannelMonitorUpdate) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) { +pub(crate) 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 +90,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 +106,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 +140,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 { @@ -142,184 +149,10 @@ pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> #[no_mangle] /// 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 res: Result = 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: 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. -#[must_use] -#[derive(Clone)] -#[repr(C)] -pub enum ChannelMonitorUpdateErr { - /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of - /// our state failed, but is expected to succeed at some point in the future). - /// - /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or - /// submitting new commitment transactions to the counterparty. Once the update(s) which failed - /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to - /// restore the channel to an operational state. - /// - /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If - /// you return a TemporaryFailure you must ensure that it is written to disk safely before - /// writing out the latest ChannelManager state. - /// - /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur - /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting - /// to claim it on this channel) and those updates must be applied wherever they can be. At - /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should - /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to - /// the channel which would invalidate previous ChannelMonitors are not made when a channel has - /// been \"frozen\". - /// - /// Note that even if updates made after TemporaryFailure succeed you must still call - /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel - /// operation. - /// - /// Note that the update being processed here will not be replayed for you when you call - /// ChannelManager::channel_monitor_updated, so you must store the update itself along - /// with the persisted ChannelMonitor on your own local disk prior to returning a - /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the - /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at - /// reload-time. - /// - /// For deployments where a copy of ChannelMonitors and other local state are backed up in a - /// remote location (with local copies persisted immediately), it is anticipated that all - /// updates will return TemporaryFailure until the remote copies could be updated. - TemporaryFailure, - /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a - /// different watchtower and cannot update with all watchtowers that were previously informed - /// of this channel). - /// - /// At reception of this error, ChannelManager will force-close the channel and return at - /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at - /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel - /// update must be rejected. - /// - /// This failure may also signal a failure to update the local persisted copy of one of - /// the channel monitor instance. - /// - /// Note that even when you fail a holder commitment transaction update, you must store the - /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor - /// broadcasts it (e.g distributed channel-monitor deployment) - /// - /// In case of distributed watchtowers deployment, the new version must be written to disk, as - /// state may have been stored but rejected due to a block forcing a commitment broadcast. This - /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower, - /// lagging behind on block processing. - PermanentFailure, -} -use lightning::chain::channelmonitor::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr; -impl ChannelMonitorUpdateErr { - #[allow(unused)] - pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr { - match self { - ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure, - ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure, - } - } - #[allow(unused)] - pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr { - match self { - ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure, - ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure, - } - } - #[allow(unused)] - pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self { - match native { - nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure, - nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure, - } - } - #[allow(unused)] - pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self { - match native { - nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure, - nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure, - } - } -} -/// Creates a copy of the ChannelMonitorUpdateErr -#[no_mangle] -pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr { - orig.clone() -} -#[no_mangle] -/// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr -pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr { - ChannelMonitorUpdateErr::TemporaryFailure} -#[no_mangle] -/// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr -pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr { - ChannelMonitorUpdateErr::PermanentFailure} - -use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport; -type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport; - -/// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is -/// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this -/// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was -/// corrupted. -/// Contains a developer-readable error message. -#[must_use] -#[repr(C)] -pub struct MonitorUpdateError { - /// A pointer to the opaque Rust object. - - /// Nearly everywhere, inner must be non-null, however in places where - /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeMonitorUpdateError, - /// Indicates that this is the only struct which contains the same pointer. - - /// Rust functions which take ownership of an object provided via an argument require - /// this to be true and invalidate the object pointed to by inner. - pub is_owned: bool, -} - -impl Drop for MonitorUpdateError { - fn drop(&mut self) { - if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(self.inner) }; - } - } -} -/// Frees any resources used by the MonitorUpdateError, if is_owned is set and inner is non-NULL. -#[no_mangle] -pub extern "C" fn MonitorUpdateError_free(this_obj: MonitorUpdateError) { } -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -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 take_inner(mut self) -> *mut nativeMonitorUpdateError { - assert!(self.is_owned); - let ret = self.inner; - self.inner = std::ptr::null_mut(); - ret - } -} -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())) }, - is_owned: true, - } - } -} -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void -} -#[no_mangle] -/// Creates a copy of the MonitorUpdateError -pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError { - orig.clone() -} /// An event to be processed by the ChannelManager. #[must_use] #[derive(Clone)] @@ -327,8 +160,27 @@ pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> Monitor pub enum MonitorEvent { /// A monitor event containing an HTLCUpdate. HTLCEvent(crate::lightning::chain::channelmonitor::HTLCUpdate), - /// A monitor event that the Channel's commitment transaction was broadcasted. - CommitmentTxBroadcasted(crate::lightning::chain::transaction::OutPoint), + /// A monitor event that the Channel's commitment transaction was confirmed. + CommitmentTxConfirmed(crate::lightning::chain::transaction::OutPoint), + /// Indicates a [`ChannelMonitor`] update has completed. See + /// [`ChannelMonitorUpdateErr::TemporaryFailure`] for more information on how this is used. + /// + /// [`ChannelMonitorUpdateErr::TemporaryFailure`]: super::ChannelMonitorUpdateErr::TemporaryFailure + UpdateCompleted { + /// The funding outpoint of the [`ChannelMonitor`] that was updated + funding_txo: crate::lightning::chain::transaction::OutPoint, + /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or + /// [`ChannelMonitor::get_latest_update_id`]. + /// + /// Note that this should only be set to a given update's ID if all previous updates for the + /// same [`ChannelMonitor`] have been applied and persisted. + monitor_update_id: u64, + }, + /// Indicates a [`ChannelMonitor`] update has failed. See + /// [`ChannelMonitorUpdateErr::PermanentFailure`] for more information on how this is used. + /// + /// [`ChannelMonitorUpdateErr::PermanentFailure`]: super::ChannelMonitorUpdateErr::PermanentFailure + UpdateFailed(crate::lightning::chain::transaction::OutPoint), } use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent; impl MonitorEvent { @@ -341,9 +193,23 @@ impl MonitorEvent { *unsafe { Box::from_raw(a_nonref.take_inner()) }, ) }, - MonitorEvent::CommitmentTxBroadcasted (ref a, ) => { + MonitorEvent::CommitmentTxConfirmed (ref a, ) => { let mut a_nonref = (*a).clone(); - nativeMonitorEvent::CommitmentTxBroadcasted ( + nativeMonitorEvent::CommitmentTxConfirmed ( + *unsafe { Box::from_raw(a_nonref.take_inner()) }, + ) + }, + MonitorEvent::UpdateCompleted {ref funding_txo, ref monitor_update_id, } => { + let mut funding_txo_nonref = (*funding_txo).clone(); + let mut monitor_update_id_nonref = (*monitor_update_id).clone(); + nativeMonitorEvent::UpdateCompleted { + funding_txo: *unsafe { Box::from_raw(funding_txo_nonref.take_inner()) }, + monitor_update_id: monitor_update_id_nonref, + } + }, + MonitorEvent::UpdateFailed (ref a, ) => { + let mut a_nonref = (*a).clone(); + nativeMonitorEvent::UpdateFailed ( *unsafe { Box::from_raw(a_nonref.take_inner()) }, ) }, @@ -357,8 +223,19 @@ impl MonitorEvent { *unsafe { Box::from_raw(a.take_inner()) }, ) }, - MonitorEvent::CommitmentTxBroadcasted (mut a, ) => { - nativeMonitorEvent::CommitmentTxBroadcasted ( + MonitorEvent::CommitmentTxConfirmed (mut a, ) => { + nativeMonitorEvent::CommitmentTxConfirmed ( + *unsafe { Box::from_raw(a.take_inner()) }, + ) + }, + MonitorEvent::UpdateCompleted {mut funding_txo, mut monitor_update_id, } => { + nativeMonitorEvent::UpdateCompleted { + funding_txo: *unsafe { Box::from_raw(funding_txo.take_inner()) }, + monitor_update_id: monitor_update_id, + } + }, + MonitorEvent::UpdateFailed (mut a, ) => { + nativeMonitorEvent::UpdateFailed ( *unsafe { Box::from_raw(a.take_inner()) }, ) }, @@ -370,13 +247,27 @@ 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, ) => { + nativeMonitorEvent::CommitmentTxConfirmed (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 }, + MonitorEvent::CommitmentTxConfirmed ( + crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, + ) + }, + nativeMonitorEvent::UpdateCompleted {ref funding_txo, ref monitor_update_id, } => { + let mut funding_txo_nonref = (*funding_txo).clone(); + let mut monitor_update_id_nonref = (*monitor_update_id).clone(); + MonitorEvent::UpdateCompleted { + funding_txo: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo_nonref), is_owned: true }, + monitor_update_id: monitor_update_id_nonref, + } + }, + nativeMonitorEvent::UpdateFailed (ref a, ) => { + let mut a_nonref = (*a).clone(); + MonitorEvent::UpdateFailed ( + crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, ) }, } @@ -386,12 +277,23 @@ 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::CommitmentTxConfirmed (mut a, ) => { + MonitorEvent::CommitmentTxConfirmed ( + crate::lightning::chain::transaction::OutPoint { 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 }, + nativeMonitorEvent::UpdateCompleted {mut funding_txo, mut monitor_update_id, } => { + MonitorEvent::UpdateCompleted { + funding_txo: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, + monitor_update_id: monitor_update_id, + } + }, + nativeMonitorEvent::UpdateFailed (mut a, ) => { + MonitorEvent::UpdateFailed ( + crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a), is_owned: true }, ) }, } @@ -411,13 +313,38 @@ pub extern "C" fn MonitorEvent_htlcevent(a: crate::lightning::chain::channelmoni MonitorEvent::HTLCEvent(a, ) } #[no_mangle] -/// Utility method to constructs a new CommitmentTxBroadcasted-variant MonitorEvent -pub extern "C" fn MonitorEvent_commitment_tx_broadcasted(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent { - MonitorEvent::CommitmentTxBroadcasted(a, ) +/// Utility method to constructs a new CommitmentTxConfirmed-variant MonitorEvent +pub extern "C" fn MonitorEvent_commitment_tx_confirmed(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent { + MonitorEvent::CommitmentTxConfirmed(a, ) +} +#[no_mangle] +/// Utility method to constructs a new UpdateCompleted-variant MonitorEvent +pub extern "C" fn MonitorEvent_update_completed(funding_txo: crate::lightning::chain::transaction::OutPoint, monitor_update_id: u64) -> MonitorEvent { + MonitorEvent::UpdateCompleted { + funding_txo, + monitor_update_id, + } +} +#[no_mangle] +/// Utility method to constructs a new UpdateFailed-variant MonitorEvent +pub extern "C" fn MonitorEvent_update_failed(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent { + MonitorEvent::UpdateFailed(a, ) +} +#[no_mangle] +/// Serialize the MonitorEvent object into a byte array which can be read by MonitorEvent_read +pub extern "C" fn MonitorEvent_write(obj: &MonitorEvent) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[no_mangle] +/// Read a MonitorEvent from a byte array, created by MonitorEvent_write +pub extern "C" fn MonitorEvent_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_MonitorEventZDecodeErrorZ { + let res: Result, lightning::ln::msgs::DecodeError> = crate::c_types::maybe_deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = if o.is_none() { crate::c_types::derived::COption_MonitorEventZ::None } else { crate::c_types::derived::COption_MonitorEventZ::Some( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(o.unwrap()) }) }; 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 } use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport; -type nativeHTLCUpdate = nativeHTLCUpdateImport; +pub(crate) type nativeHTLCUpdate = nativeHTLCUpdateImport; /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the @@ -440,7 +367,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)) }; } } } @@ -449,15 +376,21 @@ impl Drop for HTLCUpdate { pub extern "C" fn HTLCUpdate_free(this_obj: HTLCUpdate) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) { +pub(crate) 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 +399,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 +417,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 { @@ -493,18 +426,250 @@ pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_t #[no_mangle] /// 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 res: Result = 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: 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 -/// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money. +/// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding +/// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us +/// losing money. +/// +/// Note that this is a library-wide security assumption. If a reorg deeper than this number of +/// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed +/// by a [`ChannelMonitor`] may be incorrect. #[no_mangle] pub static ANTI_REORG_DELAY: u32 = lightning::chain::channelmonitor::ANTI_REORG_DELAY; +/// Details about the balance(s) available for spending once the channel appears on chain. +/// +/// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not +/// be provided. +#[must_use] +#[derive(Clone)] +#[repr(C)] +pub enum Balance { + /// The channel is not yet closed (or the commitment or closing transaction has not yet + /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is + /// force-closed now. + ClaimableOnChannelClose { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + }, + /// The channel has been closed, and the given balance is ours but awaiting confirmations until + /// we consider it spendable. + ClaimableAwaitingConfirmations { + /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which + /// were spent in broadcasting the transaction. + claimable_amount_satoshis: u64, + /// The height at which an [`Event::SpendableOutputs`] event will be generated for this + /// amount. + confirmation_height: u32, + }, + /// The channel has been closed, and the given balance should be ours but awaiting spending + /// transaction confirmation. If the spending transaction does not confirm in time, it is + /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain. + /// + /// Once the spending transaction confirms, before it has reached enough confirmations to be + /// considered safe from chain reorganizations, the balance will instead be provided via + /// [`Balance::ClaimableAwaitingConfirmations`]. + ContentiousClaimable { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + /// The height at which the counterparty may be able to claim the balance if we have not + /// done so. + timeout_height: u32, + }, + /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain + /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat + /// likely to be claimed by our counterparty before we do. + MaybeClaimableHTLCAwaitingTimeout { + /// The amount available to claim, in satoshis, excluding the on-chain fees which will be + /// required to do so. + claimable_amount_satoshis: u64, + /// The height at which we will be able to claim the balance if our counterparty has not + /// done so. + claimable_height: u32, + }, +} +use lightning::chain::channelmonitor::Balance as nativeBalance; +impl Balance { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeBalance { + match self { + Balance::ClaimableOnChannelClose {ref claimable_amount_satoshis, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + nativeBalance::ClaimableOnChannelClose { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + } + }, + Balance::ClaimableAwaitingConfirmations {ref claimable_amount_satoshis, ref confirmation_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut confirmation_height_nonref = (*confirmation_height).clone(); + nativeBalance::ClaimableAwaitingConfirmations { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + confirmation_height: confirmation_height_nonref, + } + }, + Balance::ContentiousClaimable {ref claimable_amount_satoshis, ref timeout_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut timeout_height_nonref = (*timeout_height).clone(); + nativeBalance::ContentiousClaimable { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + timeout_height: timeout_height_nonref, + } + }, + Balance::MaybeClaimableHTLCAwaitingTimeout {ref claimable_amount_satoshis, ref claimable_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut claimable_height_nonref = (*claimable_height).clone(); + nativeBalance::MaybeClaimableHTLCAwaitingTimeout { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + claimable_height: claimable_height_nonref, + } + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeBalance { + match self { + Balance::ClaimableOnChannelClose {mut claimable_amount_satoshis, } => { + nativeBalance::ClaimableOnChannelClose { + claimable_amount_satoshis: claimable_amount_satoshis, + } + }, + Balance::ClaimableAwaitingConfirmations {mut claimable_amount_satoshis, mut confirmation_height, } => { + nativeBalance::ClaimableAwaitingConfirmations { + claimable_amount_satoshis: claimable_amount_satoshis, + confirmation_height: confirmation_height, + } + }, + Balance::ContentiousClaimable {mut claimable_amount_satoshis, mut timeout_height, } => { + nativeBalance::ContentiousClaimable { + claimable_amount_satoshis: claimable_amount_satoshis, + timeout_height: timeout_height, + } + }, + Balance::MaybeClaimableHTLCAwaitingTimeout {mut claimable_amount_satoshis, mut claimable_height, } => { + nativeBalance::MaybeClaimableHTLCAwaitingTimeout { + claimable_amount_satoshis: claimable_amount_satoshis, + claimable_height: claimable_height, + } + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeBalance) -> Self { + match native { + nativeBalance::ClaimableOnChannelClose {ref claimable_amount_satoshis, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + Balance::ClaimableOnChannelClose { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + } + }, + nativeBalance::ClaimableAwaitingConfirmations {ref claimable_amount_satoshis, ref confirmation_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut confirmation_height_nonref = (*confirmation_height).clone(); + Balance::ClaimableAwaitingConfirmations { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + confirmation_height: confirmation_height_nonref, + } + }, + nativeBalance::ContentiousClaimable {ref claimable_amount_satoshis, ref timeout_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut timeout_height_nonref = (*timeout_height).clone(); + Balance::ContentiousClaimable { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + timeout_height: timeout_height_nonref, + } + }, + nativeBalance::MaybeClaimableHTLCAwaitingTimeout {ref claimable_amount_satoshis, ref claimable_height, } => { + let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone(); + let mut claimable_height_nonref = (*claimable_height).clone(); + Balance::MaybeClaimableHTLCAwaitingTimeout { + claimable_amount_satoshis: claimable_amount_satoshis_nonref, + claimable_height: claimable_height_nonref, + } + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeBalance) -> Self { + match native { + nativeBalance::ClaimableOnChannelClose {mut claimable_amount_satoshis, } => { + Balance::ClaimableOnChannelClose { + claimable_amount_satoshis: claimable_amount_satoshis, + } + }, + nativeBalance::ClaimableAwaitingConfirmations {mut claimable_amount_satoshis, mut confirmation_height, } => { + Balance::ClaimableAwaitingConfirmations { + claimable_amount_satoshis: claimable_amount_satoshis, + confirmation_height: confirmation_height, + } + }, + nativeBalance::ContentiousClaimable {mut claimable_amount_satoshis, mut timeout_height, } => { + Balance::ContentiousClaimable { + claimable_amount_satoshis: claimable_amount_satoshis, + timeout_height: timeout_height, + } + }, + nativeBalance::MaybeClaimableHTLCAwaitingTimeout {mut claimable_amount_satoshis, mut claimable_height, } => { + Balance::MaybeClaimableHTLCAwaitingTimeout { + claimable_amount_satoshis: claimable_amount_satoshis, + claimable_height: claimable_height, + } + }, + } + } +} +/// Frees any resources used by the Balance +#[no_mangle] +pub extern "C" fn Balance_free(this_ptr: Balance) { } +/// Creates a copy of the Balance +#[no_mangle] +pub extern "C" fn Balance_clone(orig: &Balance) -> Balance { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new ClaimableOnChannelClose-variant Balance +pub extern "C" fn Balance_claimable_on_channel_close(claimable_amount_satoshis: u64) -> Balance { + Balance::ClaimableOnChannelClose { + claimable_amount_satoshis, + } +} +#[no_mangle] +/// Utility method to constructs a new ClaimableAwaitingConfirmations-variant Balance +pub extern "C" fn Balance_claimable_awaiting_confirmations(claimable_amount_satoshis: u64, confirmation_height: u32) -> Balance { + Balance::ClaimableAwaitingConfirmations { + claimable_amount_satoshis, + confirmation_height, + } +} +#[no_mangle] +/// Utility method to constructs a new ContentiousClaimable-variant Balance +pub extern "C" fn Balance_contentious_claimable(claimable_amount_satoshis: u64, timeout_height: u32) -> Balance { + Balance::ContentiousClaimable { + claimable_amount_satoshis, + timeout_height, + } +} +#[no_mangle] +/// Utility method to constructs a new MaybeClaimableHTLCAwaitingTimeout-variant Balance +pub extern "C" fn Balance_maybe_claimable_htlcawaiting_timeout(claimable_amount_satoshis: u64, claimable_height: u32) -> Balance { + Balance::MaybeClaimableHTLCAwaitingTimeout { + claimable_amount_satoshis, + claimable_height, + } +} +/// Checks if two Balances contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn Balance_eq(a: &Balance, b: &Balance) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport; -type nativeChannelMonitor = nativeChannelMonitorImport; +pub(crate) type nativeChannelMonitor = nativeChannelMonitorImport; /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates /// on-chain transactions to ensure no loss of funds occurs. @@ -540,7 +705,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)) }; } } } @@ -549,15 +714,21 @@ impl Drop for ChannelMonitor { pub extern "C" fn ChannelMonitor_free(this_obj: ChannelMonitor) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) { +pub(crate) 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 +736,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 { @@ -577,9 +748,9 @@ pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate: /// panics if the given update is not the next update by update_id. #[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() }; +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_NoneNoneZ { + 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( { () /*e*/ }).into() }; local_ret } @@ -588,7 +759,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 +767,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 +777,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 +787,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 +795,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 +809,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 +826,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 +846,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 +855,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 +869,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 +882,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 +895,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 +904,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,113 +914,37 @@ 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 -/// writing once to disk, and/or uploading to one or more backup services. +/// Gets the balances in this channel which are either claimable by us if we were to +/// force-close the channel now or which are claimable on-chain (possibly awaiting +/// confirmation). /// -/// Note that for every new monitor, you **must** persist the new `ChannelMonitor` -/// to disk/backups. And, on every update, you **must** persist either the -/// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk -/// of situations such as revoking a transaction, then crashing before this -/// revocation can be persisted, then unintentionally broadcasting a revoked -/// transaction and losing money. This is a risk because previous channel states -/// are toxic, so it's important that whatever channel state is persisted is -/// kept up-to-date. -#[repr(C)] -pub struct Persist { - /// An opaque pointer which is passed to your function implementations as an argument. - /// This has no meaning in the LDK, and can be NULL or any other value. - pub this_arg: *mut c_void, - /// Persist a new channel's data. The data can be stored any way you want, but - /// the identifier provided by Rust-Lightning is the channel's outpoint (and - /// it is up to you to maintain a correct mapping between the outpoint and the - /// stored channel data). Note that you **must** persist every new monitor to - /// disk. See the `Persist` trait documentation for more details. - /// - /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`, - /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors. - #[must_use] - pub persist_new_channel: extern "C" fn (this_arg: *const c_void, id: crate::lightning::chain::transaction::OutPoint, data: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ, - /// Update one channel's data. The provided `ChannelMonitor` has already - /// applied the given update. - /// - /// Note that on every update, you **must** persist either the - /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See - /// the `Persist` trait documentation for more details. - /// - /// If an implementer chooses to persist the updates only, they need to make - /// sure that all the updates are applied to the `ChannelMonitors` *before* - /// the set of channel monitors is given to the `ChannelManager` - /// deserialization routine. See [`ChannelMonitor::update_monitor`] for - /// applying a monitor update to a monitor. If full `ChannelMonitors` are - /// persisted, then there is no need to persist individual updates. - /// - /// Note that there could be a performance tradeoff between persisting complete - /// channel monitors on every update vs. persisting only updates and applying - /// them in batches. The size of each monitor grows `O(number of state updates)` - /// whereas updates are small and `O(1)`. - /// - /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`, - /// [`ChannelMonitorUpdate::write`] for writing out an update, and - /// [`ChannelMonitorUpdateErr`] for requirements when returning errors. - #[must_use] - pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, id: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ, - /// Frees any resources associated with this object given its this_arg pointer. - /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. - pub free: Option, -} -unsafe impl Send for Persist {} -unsafe impl Sync for Persist {} -#[no_mangle] -pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist { - Persist { - this_arg: orig.this_arg, - persist_new_channel: Clone::clone(&orig.persist_new_channel), - update_persisted_channel: Clone::clone(&orig.update_persisted_channel), - free: Clone::clone(&orig.free), - } -} - -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 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 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 - } -} - -// We're essentially a pointer already, or at least a set of pointers, so allow us to be used -// directly as a Deref trait in higher-level structs: -impl std::ops::Deref for Persist { - type Target = Self; - fn deref(&self) -> &Self { - self - } -} -/// Calls the free function if one is set +/// Any balances in the channel which are available on-chain (excluding on-chain fees) are +/// included here until an [`Event::SpendableOutputs`] event has been generated for the +/// balance, or until our counterparty has claimed the balance and accrued several +/// confirmations on the claim transaction. +/// +/// Note that the balances available when you or your counterparty have broadcasted revoked +/// state(s) may not be fully captured here. +/// +/// See [`Balance`] for additional details on the types of claimable balances which +/// may be returned here and their meanings. +#[must_use] #[no_mangle] -pub extern "C" fn Persist_free(this_ptr: Persist) { } -impl Drop for Persist { - fn drop(&mut self) { - if let Some(f) = self.free { - f(self.this_arg); - } - } +pub extern "C" fn ChannelMonitor_get_claimable_balances(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_BalanceZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_claimable_balances(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::Balance::native_into(item) }); }; + local_ret.into() } + #[no_mangle] /// Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write 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 }