1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
9 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
12 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
13 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
14 //! be made in responding to certain messages, see [`chain::Watch`] for more.
16 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
17 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
18 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
19 //! security-domain-separated system design, you should consider having multiple paths for
20 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
22 use alloc::str::FromStr;
23 use alloc::string::String;
24 use core::ffi::c_void;
25 use core::convert::Infallible;
26 use bitcoin::hashes::Hash;
27 use crate::c_types::*;
28 #[cfg(feature="no-std")]
29 use alloc::{vec::Vec, boxed::Box};
32 use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport;
33 pub(crate) type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport;
35 /// An update generated by the underlying channel itself which contains some new information the
36 /// [`ChannelMonitor`] should be made aware of.
38 /// Because this represents only a small number of updates to the underlying state, it is generally
39 /// much smaller than a full [`ChannelMonitor`]. However, for large single commitment transaction
40 /// updates (e.g. ones during which there are hundreds of HTLCs pending on the commitment
41 /// transaction), a single update may reach upwards of 1 MiB in serialized size.
44 pub struct ChannelMonitorUpdate {
45 /// A pointer to the opaque Rust object.
47 /// Nearly everywhere, inner must be non-null, however in places where
48 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
49 pub inner: *mut nativeChannelMonitorUpdate,
50 /// Indicates that this is the only struct which contains the same pointer.
52 /// Rust functions which take ownership of an object provided via an argument require
53 /// this to be true and invalidate the object pointed to by inner.
57 impl Drop for ChannelMonitorUpdate {
59 if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
60 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
64 /// Frees any resources used by the ChannelMonitorUpdate, if is_owned is set and inner is non-NULL.
66 pub extern "C" fn ChannelMonitorUpdate_free(this_obj: ChannelMonitorUpdate) { }
68 /// Used only if an object of this type is returned as a trait impl by a method
69 pub(crate) extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
70 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate) };
73 impl ChannelMonitorUpdate {
74 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitorUpdate {
75 unsafe { &*ObjOps::untweak_ptr(self.inner) }
77 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitorUpdate {
78 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
80 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
81 pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
82 assert!(self.is_owned);
83 let ret = ObjOps::untweak_ptr(self.inner);
84 self.inner = core::ptr::null_mut();
88 /// The sequence number of this update. Updates *must* be replayed in-order according to this
89 /// sequence number (and updates may panic if they are not). The update_id values are strictly
90 /// increasing and increase by one for each new update, with two exceptions specified below.
92 /// This sequence number is also used to track up to which points updates which returned
93 /// [`ChannelMonitorUpdateStatus::InProgress`] have been applied to all copies of a given
94 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
96 /// The only instances we allow where update_id values are not strictly increasing have a
97 /// special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. This update ID is used for updates that
98 /// will force close the channel by broadcasting the latest commitment transaction or
99 /// special post-force-close updates, like providing preimages necessary to claim outputs on the
100 /// broadcast commitment transaction. See its docs for more details.
102 /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
104 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
105 let mut inner_val = &mut this_ptr.get_native_mut_ref().update_id;
108 /// The sequence number of this update. Updates *must* be replayed in-order according to this
109 /// sequence number (and updates may panic if they are not). The update_id values are strictly
110 /// increasing and increase by one for each new update, with two exceptions specified below.
112 /// This sequence number is also used to track up to which points updates which returned
113 /// [`ChannelMonitorUpdateStatus::InProgress`] have been applied to all copies of a given
114 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
116 /// The only instances we allow where update_id values are not strictly increasing have a
117 /// special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. This update ID is used for updates that
118 /// will force close the channel by broadcasting the latest commitment transaction or
119 /// special post-force-close updates, like providing preimages necessary to claim outputs on the
120 /// broadcast commitment transaction. See its docs for more details.
122 /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
124 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
125 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_id = val;
127 impl Clone for ChannelMonitorUpdate {
128 fn clone(&self) -> Self {
130 inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { core::ptr::null_mut() } else {
131 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
137 /// Used only if an object of this type is returned as a trait impl by a method
138 pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
139 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelMonitorUpdate)).clone() })) as *mut c_void
142 /// Creates a copy of the ChannelMonitorUpdate
143 pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
146 /// Checks if two ChannelMonitorUpdates contain equal inner contents.
147 /// This ignores pointers and is_owned flags and looks at the values in fields.
148 /// Two objects with NULL inner values will be considered "equal" here.
150 pub extern "C" fn ChannelMonitorUpdate_eq(a: &ChannelMonitorUpdate, b: &ChannelMonitorUpdate) -> bool {
151 if a.inner == b.inner { return true; }
152 if a.inner.is_null() || b.inner.is_null() { return false; }
153 if a.get_native_ref() == b.get_native_ref() { true } else { false }
155 /// The update ID used for a [`ChannelMonitorUpdate`] that is either:
157 ///\t(1) attempting to force close the channel by broadcasting our latest commitment transaction or
158 ///\t(2) providing a preimage (after the channel has been force closed) from a forward link that
159 ///\t\tallows us to spend an HTLC output on this channel's (the backward link's) broadcasted
160 ///\t\tcommitment transaction.
162 /// No other [`ChannelMonitorUpdate`]s are allowed after force-close.
165 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
167 /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read
168 pub extern "C" fn ChannelMonitorUpdate_write(obj: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
169 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
172 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
173 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
176 /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write
177 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
178 let res: Result<lightning::chain::channelmonitor::ChannelMonitorUpdate, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
179 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::native_into(e) }).into() };
182 /// An event to be processed by the ChannelManager.
186 pub enum MonitorEvent {
187 /// A monitor event containing an HTLCUpdate.
189 crate::lightning::chain::channelmonitor::HTLCUpdate),
190 /// A monitor event that the Channel's commitment transaction was confirmed.
192 crate::lightning::chain::transaction::OutPoint),
193 /// Indicates a [`ChannelMonitor`] update has completed. See
194 /// [`ChannelMonitorUpdateStatus::InProgress`] for more information on how this is used.
196 /// [`ChannelMonitorUpdateStatus::InProgress`]: super::ChannelMonitorUpdateStatus::InProgress
198 /// The funding outpoint of the [`ChannelMonitor`] that was updated
199 funding_txo: crate::lightning::chain::transaction::OutPoint,
200 /// The Update ID from [`ChannelMonitorUpdate::update_id`] which was applied or
201 /// [`ChannelMonitor::get_latest_update_id`].
203 /// Note that this should only be set to a given update's ID if all previous updates for the
204 /// same [`ChannelMonitor`] have been applied and persisted.
205 monitor_update_id: u64,
208 use lightning::chain::channelmonitor::MonitorEvent as MonitorEventImport;
209 pub(crate) type nativeMonitorEvent = MonitorEventImport;
213 pub(crate) fn to_native(&self) -> nativeMonitorEvent {
215 MonitorEvent::HTLCEvent (ref a, ) => {
216 let mut a_nonref = Clone::clone(a);
217 nativeMonitorEvent::HTLCEvent (
218 *unsafe { Box::from_raw(a_nonref.take_inner()) },
221 MonitorEvent::HolderForceClosed (ref a, ) => {
222 let mut a_nonref = Clone::clone(a);
223 nativeMonitorEvent::HolderForceClosed (
224 *unsafe { Box::from_raw(a_nonref.take_inner()) },
227 MonitorEvent::Completed {ref funding_txo, ref monitor_update_id, } => {
228 let mut funding_txo_nonref = Clone::clone(funding_txo);
229 let mut monitor_update_id_nonref = Clone::clone(monitor_update_id);
230 nativeMonitorEvent::Completed {
231 funding_txo: *unsafe { Box::from_raw(funding_txo_nonref.take_inner()) },
232 monitor_update_id: monitor_update_id_nonref,
238 pub(crate) fn into_native(self) -> nativeMonitorEvent {
240 MonitorEvent::HTLCEvent (mut a, ) => {
241 nativeMonitorEvent::HTLCEvent (
242 *unsafe { Box::from_raw(a.take_inner()) },
245 MonitorEvent::HolderForceClosed (mut a, ) => {
246 nativeMonitorEvent::HolderForceClosed (
247 *unsafe { Box::from_raw(a.take_inner()) },
250 MonitorEvent::Completed {mut funding_txo, mut monitor_update_id, } => {
251 nativeMonitorEvent::Completed {
252 funding_txo: *unsafe { Box::from_raw(funding_txo.take_inner()) },
253 monitor_update_id: monitor_update_id,
259 pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
261 nativeMonitorEvent::HTLCEvent (ref a, ) => {
262 let mut a_nonref = Clone::clone(a);
263 MonitorEvent::HTLCEvent (
264 crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
267 nativeMonitorEvent::HolderForceClosed (ref a, ) => {
268 let mut a_nonref = Clone::clone(a);
269 MonitorEvent::HolderForceClosed (
270 crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
273 nativeMonitorEvent::Completed {ref funding_txo, ref monitor_update_id, } => {
274 let mut funding_txo_nonref = Clone::clone(funding_txo);
275 let mut monitor_update_id_nonref = Clone::clone(monitor_update_id);
276 MonitorEvent::Completed {
277 funding_txo: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo_nonref), is_owned: true },
278 monitor_update_id: monitor_update_id_nonref,
284 pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
286 nativeMonitorEvent::HTLCEvent (mut a, ) => {
287 MonitorEvent::HTLCEvent (
288 crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a), is_owned: true },
291 nativeMonitorEvent::HolderForceClosed (mut a, ) => {
292 MonitorEvent::HolderForceClosed (
293 crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a), is_owned: true },
296 nativeMonitorEvent::Completed {mut funding_txo, mut monitor_update_id, } => {
297 MonitorEvent::Completed {
298 funding_txo: crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true },
299 monitor_update_id: monitor_update_id,
305 /// Frees any resources used by the MonitorEvent
307 pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
308 /// Creates a copy of the MonitorEvent
310 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
314 /// Used only if an object of this type is returned as a trait impl by a method
315 pub(crate) extern "C" fn MonitorEvent_clone_void(this_ptr: *const c_void) -> *mut c_void {
316 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const MonitorEvent)).clone() })) as *mut c_void
319 /// Used only if an object of this type is returned as a trait impl by a method
320 pub(crate) extern "C" fn MonitorEvent_free_void(this_ptr: *mut c_void) {
321 let _ = unsafe { Box::from_raw(this_ptr as *mut MonitorEvent) };
324 /// Utility method to constructs a new HTLCEvent-variant MonitorEvent
325 pub extern "C" fn MonitorEvent_htlcevent(a: crate::lightning::chain::channelmonitor::HTLCUpdate) -> MonitorEvent {
326 MonitorEvent::HTLCEvent(a, )
329 /// Utility method to constructs a new HolderForceClosed-variant MonitorEvent
330 pub extern "C" fn MonitorEvent_holder_force_closed(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent {
331 MonitorEvent::HolderForceClosed(a, )
334 /// Utility method to constructs a new Completed-variant MonitorEvent
335 pub extern "C" fn MonitorEvent_completed(funding_txo: crate::lightning::chain::transaction::OutPoint, monitor_update_id: u64) -> MonitorEvent {
336 MonitorEvent::Completed {
341 /// Checks if two MonitorEvents contain equal inner contents.
342 /// This ignores pointers and is_owned flags and looks at the values in fields.
344 pub extern "C" fn MonitorEvent_eq(a: &MonitorEvent, b: &MonitorEvent) -> bool {
345 if &a.to_native() == &b.to_native() { true } else { false }
348 /// Serialize the MonitorEvent object into a byte array which can be read by MonitorEvent_read
349 pub extern "C" fn MonitorEvent_write(obj: &crate::lightning::chain::channelmonitor::MonitorEvent) -> crate::c_types::derived::CVec_u8Z {
350 crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
353 pub(crate) extern "C" fn MonitorEvent_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
354 MonitorEvent_write(unsafe { &*(obj as *const MonitorEvent) })
357 /// Read a MonitorEvent from a byte array, created by MonitorEvent_write
358 pub extern "C" fn MonitorEvent_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_MonitorEventZDecodeErrorZ {
359 let res: Result<Option<lightning::chain::channelmonitor::MonitorEvent>, lightning::ln::msgs::DecodeError> = crate::c_types::maybe_deserialize_obj(ser);
360 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::native_into(e) }).into() };
364 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
365 pub(crate) type nativeHTLCUpdate = nativeHTLCUpdateImport;
367 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
368 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
369 /// preimage claim backward will lead to loss of funds.
372 pub struct HTLCUpdate {
373 /// A pointer to the opaque Rust object.
375 /// Nearly everywhere, inner must be non-null, however in places where
376 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
377 pub inner: *mut nativeHTLCUpdate,
378 /// Indicates that this is the only struct which contains the same pointer.
380 /// Rust functions which take ownership of an object provided via an argument require
381 /// this to be true and invalidate the object pointed to by inner.
385 impl Drop for HTLCUpdate {
387 if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
388 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
392 /// Frees any resources used by the HTLCUpdate, if is_owned is set and inner is non-NULL.
394 pub extern "C" fn HTLCUpdate_free(this_obj: HTLCUpdate) { }
396 /// Used only if an object of this type is returned as a trait impl by a method
397 pub(crate) extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
398 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeHTLCUpdate) };
402 pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCUpdate {
403 unsafe { &*ObjOps::untweak_ptr(self.inner) }
405 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCUpdate {
406 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
408 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
409 pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
410 assert!(self.is_owned);
411 let ret = ObjOps::untweak_ptr(self.inner);
412 self.inner = core::ptr::null_mut();
416 impl Clone for HTLCUpdate {
417 fn clone(&self) -> Self {
419 inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { core::ptr::null_mut() } else {
420 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
426 /// Used only if an object of this type is returned as a trait impl by a method
427 pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
428 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeHTLCUpdate)).clone() })) as *mut c_void
431 /// Creates a copy of the HTLCUpdate
432 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
435 /// Checks if two HTLCUpdates contain equal inner contents.
436 /// This ignores pointers and is_owned flags and looks at the values in fields.
437 /// Two objects with NULL inner values will be considered "equal" here.
439 pub extern "C" fn HTLCUpdate_eq(a: &HTLCUpdate, b: &HTLCUpdate) -> bool {
440 if a.inner == b.inner { return true; }
441 if a.inner.is_null() || b.inner.is_null() { return false; }
442 if a.get_native_ref() == b.get_native_ref() { true } else { false }
445 /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read
446 pub extern "C" fn HTLCUpdate_write(obj: &crate::lightning::chain::channelmonitor::HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
447 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
450 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
451 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
454 /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write
455 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
456 let res: Result<lightning::chain::channelmonitor::HTLCUpdate, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
457 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::native_into(e) }).into() };
460 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
461 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
464 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
465 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
466 /// by a [`ChannelMonitor`] may be incorrect.
469 pub static ANTI_REORG_DELAY: u32 = lightning::chain::channelmonitor::ANTI_REORG_DELAY;
470 /// Details about the balance(s) available for spending once the channel appears on chain.
472 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
478 /// The channel is not yet closed (or the commitment or closing transaction has not yet
479 /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
480 /// force-closed now.
481 ClaimableOnChannelClose {
482 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
483 /// required to do so.
484 amount_satoshis: u64,
486 /// The channel has been closed, and the given balance is ours but awaiting confirmations until
487 /// we consider it spendable.
488 ClaimableAwaitingConfirmations {
489 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
490 /// were spent in broadcasting the transaction.
491 amount_satoshis: u64,
492 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
494 confirmation_height: u32,
496 /// The channel has been closed, and the given balance should be ours but awaiting spending
497 /// transaction confirmation. If the spending transaction does not confirm in time, it is
498 /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
500 /// Once the spending transaction confirms, before it has reached enough confirmations to be
501 /// considered safe from chain reorganizations, the balance will instead be provided via
502 /// [`Balance::ClaimableAwaitingConfirmations`].
503 ContentiousClaimable {
504 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
505 /// required to do so.
506 amount_satoshis: u64,
507 /// The height at which the counterparty may be able to claim the balance if we have not
510 /// The payment hash that locks this HTLC.
511 payment_hash: crate::c_types::ThirtyTwoBytes,
512 /// The preimage that can be used to claim this HTLC.
513 payment_preimage: crate::c_types::ThirtyTwoBytes,
515 /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
516 /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
517 /// likely to be claimed by our counterparty before we do.
518 MaybeTimeoutClaimableHTLC {
519 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
520 /// which will be required to do so.
521 amount_satoshis: u64,
522 /// The height at which we will be able to claim the balance if our counterparty has not
524 claimable_height: u32,
525 /// The payment hash whose preimage our counterparty needs to claim this HTLC.
526 payment_hash: crate::c_types::ThirtyTwoBytes,
528 /// HTLCs which we received from our counterparty which are claimable with a preimage which we
529 /// do not currently have. This will only be claimable if we receive the preimage from the node
530 /// to which we forwarded this HTLC before the timeout.
531 MaybePreimageClaimableHTLC {
532 /// The amount potentially available to claim, in satoshis, excluding the on-chain fees
533 /// which will be required to do so.
534 amount_satoshis: u64,
535 /// The height at which our counterparty will be able to claim the balance if we have not
536 /// yet received the preimage and claimed it ourselves.
538 /// The payment hash whose preimage we need to claim this HTLC.
539 payment_hash: crate::c_types::ThirtyTwoBytes,
541 /// The channel has been closed, and our counterparty broadcasted a revoked commitment
544 /// Thus, we're able to claim all outputs in the commitment transaction, one of which has the
545 /// following amount.
546 CounterpartyRevokedOutputClaimable {
547 /// The amount, in satoshis, of the output which we can claim.
549 /// Note that for outputs from HTLC balances this may be excluding some on-chain fees that
550 /// were already spent.
551 amount_satoshis: u64,
554 use lightning::chain::channelmonitor::Balance as BalanceImport;
555 pub(crate) type nativeBalance = BalanceImport;
559 pub(crate) fn to_native(&self) -> nativeBalance {
561 Balance::ClaimableOnChannelClose {ref amount_satoshis, } => {
562 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
563 nativeBalance::ClaimableOnChannelClose {
564 amount_satoshis: amount_satoshis_nonref,
567 Balance::ClaimableAwaitingConfirmations {ref amount_satoshis, ref confirmation_height, } => {
568 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
569 let mut confirmation_height_nonref = Clone::clone(confirmation_height);
570 nativeBalance::ClaimableAwaitingConfirmations {
571 amount_satoshis: amount_satoshis_nonref,
572 confirmation_height: confirmation_height_nonref,
575 Balance::ContentiousClaimable {ref amount_satoshis, ref timeout_height, ref payment_hash, ref payment_preimage, } => {
576 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
577 let mut timeout_height_nonref = Clone::clone(timeout_height);
578 let mut payment_hash_nonref = Clone::clone(payment_hash);
579 let mut payment_preimage_nonref = Clone::clone(payment_preimage);
580 nativeBalance::ContentiousClaimable {
581 amount_satoshis: amount_satoshis_nonref,
582 timeout_height: timeout_height_nonref,
583 payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data),
584 payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage_nonref.data),
587 Balance::MaybeTimeoutClaimableHTLC {ref amount_satoshis, ref claimable_height, ref payment_hash, } => {
588 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
589 let mut claimable_height_nonref = Clone::clone(claimable_height);
590 let mut payment_hash_nonref = Clone::clone(payment_hash);
591 nativeBalance::MaybeTimeoutClaimableHTLC {
592 amount_satoshis: amount_satoshis_nonref,
593 claimable_height: claimable_height_nonref,
594 payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data),
597 Balance::MaybePreimageClaimableHTLC {ref amount_satoshis, ref expiry_height, ref payment_hash, } => {
598 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
599 let mut expiry_height_nonref = Clone::clone(expiry_height);
600 let mut payment_hash_nonref = Clone::clone(payment_hash);
601 nativeBalance::MaybePreimageClaimableHTLC {
602 amount_satoshis: amount_satoshis_nonref,
603 expiry_height: expiry_height_nonref,
604 payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data),
607 Balance::CounterpartyRevokedOutputClaimable {ref amount_satoshis, } => {
608 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
609 nativeBalance::CounterpartyRevokedOutputClaimable {
610 amount_satoshis: amount_satoshis_nonref,
616 pub(crate) fn into_native(self) -> nativeBalance {
618 Balance::ClaimableOnChannelClose {mut amount_satoshis, } => {
619 nativeBalance::ClaimableOnChannelClose {
620 amount_satoshis: amount_satoshis,
623 Balance::ClaimableAwaitingConfirmations {mut amount_satoshis, mut confirmation_height, } => {
624 nativeBalance::ClaimableAwaitingConfirmations {
625 amount_satoshis: amount_satoshis,
626 confirmation_height: confirmation_height,
629 Balance::ContentiousClaimable {mut amount_satoshis, mut timeout_height, mut payment_hash, mut payment_preimage, } => {
630 nativeBalance::ContentiousClaimable {
631 amount_satoshis: amount_satoshis,
632 timeout_height: timeout_height,
633 payment_hash: ::lightning::ln::PaymentHash(payment_hash.data),
634 payment_preimage: ::lightning::ln::PaymentPreimage(payment_preimage.data),
637 Balance::MaybeTimeoutClaimableHTLC {mut amount_satoshis, mut claimable_height, mut payment_hash, } => {
638 nativeBalance::MaybeTimeoutClaimableHTLC {
639 amount_satoshis: amount_satoshis,
640 claimable_height: claimable_height,
641 payment_hash: ::lightning::ln::PaymentHash(payment_hash.data),
644 Balance::MaybePreimageClaimableHTLC {mut amount_satoshis, mut expiry_height, mut payment_hash, } => {
645 nativeBalance::MaybePreimageClaimableHTLC {
646 amount_satoshis: amount_satoshis,
647 expiry_height: expiry_height,
648 payment_hash: ::lightning::ln::PaymentHash(payment_hash.data),
651 Balance::CounterpartyRevokedOutputClaimable {mut amount_satoshis, } => {
652 nativeBalance::CounterpartyRevokedOutputClaimable {
653 amount_satoshis: amount_satoshis,
659 pub(crate) fn from_native(native: &nativeBalance) -> Self {
661 nativeBalance::ClaimableOnChannelClose {ref amount_satoshis, } => {
662 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
663 Balance::ClaimableOnChannelClose {
664 amount_satoshis: amount_satoshis_nonref,
667 nativeBalance::ClaimableAwaitingConfirmations {ref amount_satoshis, ref confirmation_height, } => {
668 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
669 let mut confirmation_height_nonref = Clone::clone(confirmation_height);
670 Balance::ClaimableAwaitingConfirmations {
671 amount_satoshis: amount_satoshis_nonref,
672 confirmation_height: confirmation_height_nonref,
675 nativeBalance::ContentiousClaimable {ref amount_satoshis, ref timeout_height, ref payment_hash, ref payment_preimage, } => {
676 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
677 let mut timeout_height_nonref = Clone::clone(timeout_height);
678 let mut payment_hash_nonref = Clone::clone(payment_hash);
679 let mut payment_preimage_nonref = Clone::clone(payment_preimage);
680 Balance::ContentiousClaimable {
681 amount_satoshis: amount_satoshis_nonref,
682 timeout_height: timeout_height_nonref,
683 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
684 payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage_nonref.0 },
687 nativeBalance::MaybeTimeoutClaimableHTLC {ref amount_satoshis, ref claimable_height, ref payment_hash, } => {
688 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
689 let mut claimable_height_nonref = Clone::clone(claimable_height);
690 let mut payment_hash_nonref = Clone::clone(payment_hash);
691 Balance::MaybeTimeoutClaimableHTLC {
692 amount_satoshis: amount_satoshis_nonref,
693 claimable_height: claimable_height_nonref,
694 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
697 nativeBalance::MaybePreimageClaimableHTLC {ref amount_satoshis, ref expiry_height, ref payment_hash, } => {
698 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
699 let mut expiry_height_nonref = Clone::clone(expiry_height);
700 let mut payment_hash_nonref = Clone::clone(payment_hash);
701 Balance::MaybePreimageClaimableHTLC {
702 amount_satoshis: amount_satoshis_nonref,
703 expiry_height: expiry_height_nonref,
704 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
707 nativeBalance::CounterpartyRevokedOutputClaimable {ref amount_satoshis, } => {
708 let mut amount_satoshis_nonref = Clone::clone(amount_satoshis);
709 Balance::CounterpartyRevokedOutputClaimable {
710 amount_satoshis: amount_satoshis_nonref,
716 pub(crate) fn native_into(native: nativeBalance) -> Self {
718 nativeBalance::ClaimableOnChannelClose {mut amount_satoshis, } => {
719 Balance::ClaimableOnChannelClose {
720 amount_satoshis: amount_satoshis,
723 nativeBalance::ClaimableAwaitingConfirmations {mut amount_satoshis, mut confirmation_height, } => {
724 Balance::ClaimableAwaitingConfirmations {
725 amount_satoshis: amount_satoshis,
726 confirmation_height: confirmation_height,
729 nativeBalance::ContentiousClaimable {mut amount_satoshis, mut timeout_height, mut payment_hash, mut payment_preimage, } => {
730 Balance::ContentiousClaimable {
731 amount_satoshis: amount_satoshis,
732 timeout_height: timeout_height,
733 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
734 payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage.0 },
737 nativeBalance::MaybeTimeoutClaimableHTLC {mut amount_satoshis, mut claimable_height, mut payment_hash, } => {
738 Balance::MaybeTimeoutClaimableHTLC {
739 amount_satoshis: amount_satoshis,
740 claimable_height: claimable_height,
741 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
744 nativeBalance::MaybePreimageClaimableHTLC {mut amount_satoshis, mut expiry_height, mut payment_hash, } => {
745 Balance::MaybePreimageClaimableHTLC {
746 amount_satoshis: amount_satoshis,
747 expiry_height: expiry_height,
748 payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
751 nativeBalance::CounterpartyRevokedOutputClaimable {mut amount_satoshis, } => {
752 Balance::CounterpartyRevokedOutputClaimable {
753 amount_satoshis: amount_satoshis,
759 /// Frees any resources used by the Balance
761 pub extern "C" fn Balance_free(this_ptr: Balance) { }
762 /// Creates a copy of the Balance
764 pub extern "C" fn Balance_clone(orig: &Balance) -> Balance {
768 /// Used only if an object of this type is returned as a trait impl by a method
769 pub(crate) extern "C" fn Balance_clone_void(this_ptr: *const c_void) -> *mut c_void {
770 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const Balance)).clone() })) as *mut c_void
773 /// Used only if an object of this type is returned as a trait impl by a method
774 pub(crate) extern "C" fn Balance_free_void(this_ptr: *mut c_void) {
775 let _ = unsafe { Box::from_raw(this_ptr as *mut Balance) };
778 /// Utility method to constructs a new ClaimableOnChannelClose-variant Balance
779 pub extern "C" fn Balance_claimable_on_channel_close(amount_satoshis: u64) -> Balance {
780 Balance::ClaimableOnChannelClose {
785 /// Utility method to constructs a new ClaimableAwaitingConfirmations-variant Balance
786 pub extern "C" fn Balance_claimable_awaiting_confirmations(amount_satoshis: u64, confirmation_height: u32) -> Balance {
787 Balance::ClaimableAwaitingConfirmations {
793 /// Utility method to constructs a new ContentiousClaimable-variant Balance
794 pub extern "C" fn Balance_contentious_claimable(amount_satoshis: u64, timeout_height: u32, payment_hash: crate::c_types::ThirtyTwoBytes, payment_preimage: crate::c_types::ThirtyTwoBytes) -> Balance {
795 Balance::ContentiousClaimable {
803 /// Utility method to constructs a new MaybeTimeoutClaimableHTLC-variant Balance
804 pub extern "C" fn Balance_maybe_timeout_claimable_htlc(amount_satoshis: u64, claimable_height: u32, payment_hash: crate::c_types::ThirtyTwoBytes) -> Balance {
805 Balance::MaybeTimeoutClaimableHTLC {
812 /// Utility method to constructs a new MaybePreimageClaimableHTLC-variant Balance
813 pub extern "C" fn Balance_maybe_preimage_claimable_htlc(amount_satoshis: u64, expiry_height: u32, payment_hash: crate::c_types::ThirtyTwoBytes) -> Balance {
814 Balance::MaybePreimageClaimableHTLC {
821 /// Utility method to constructs a new CounterpartyRevokedOutputClaimable-variant Balance
822 pub extern "C" fn Balance_counterparty_revoked_output_claimable(amount_satoshis: u64) -> Balance {
823 Balance::CounterpartyRevokedOutputClaimable {
827 /// Checks if two Balances contain equal inner contents.
828 /// This ignores pointers and is_owned flags and looks at the values in fields.
830 pub extern "C" fn Balance_eq(a: &Balance, b: &Balance) -> bool {
831 if &a.to_native() == &b.to_native() { true } else { false }
833 /// The amount claimable, in satoshis. This excludes balances that we are unsure if we are able
834 /// to claim, this is because we are waiting for a preimage or for a timeout to expire. For more
835 /// information on these balances see [`Balance::MaybeTimeoutClaimableHTLC`] and
836 /// [`Balance::MaybePreimageClaimableHTLC`].
838 /// On-chain fees required to claim the balance are not included in this amount.
841 pub extern "C" fn Balance_claimable_amount_satoshis(this_arg: &crate::lightning::chain::channelmonitor::Balance) -> u64 {
842 let mut ret = this_arg.to_native().claimable_amount_satoshis();
847 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
848 pub(crate) type nativeChannelMonitor = nativeChannelMonitorImport<crate::lightning::sign::WriteableEcdsaChannelSigner>;
850 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
851 /// on-chain transactions to ensure no loss of funds occurs.
853 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
854 /// information and are actively monitoring the chain.
856 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
857 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
858 /// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
859 /// returned block hash and the the current chain and then reconnecting blocks to get to the
860 /// best chain) upon deserializing the object!
863 pub struct ChannelMonitor {
864 /// A pointer to the opaque Rust object.
866 /// Nearly everywhere, inner must be non-null, however in places where
867 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
868 pub inner: *mut nativeChannelMonitor,
869 /// Indicates that this is the only struct which contains the same pointer.
871 /// Rust functions which take ownership of an object provided via an argument require
872 /// this to be true and invalidate the object pointed to by inner.
876 impl Drop for ChannelMonitor {
878 if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
879 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
883 /// Frees any resources used by the ChannelMonitor, if is_owned is set and inner is non-NULL.
885 pub extern "C" fn ChannelMonitor_free(this_obj: ChannelMonitor) { }
887 /// Used only if an object of this type is returned as a trait impl by a method
888 pub(crate) extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
889 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelMonitor) };
892 impl ChannelMonitor {
893 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitor {
894 unsafe { &*ObjOps::untweak_ptr(self.inner) }
896 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitor {
897 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
899 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
900 pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
901 assert!(self.is_owned);
902 let ret = ObjOps::untweak_ptr(self.inner);
903 self.inner = core::ptr::null_mut();
907 impl Clone for ChannelMonitor {
908 fn clone(&self) -> Self {
910 inner: if <*mut nativeChannelMonitor>::is_null(self.inner) { core::ptr::null_mut() } else {
911 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
917 /// Used only if an object of this type is returned as a trait impl by a method
918 pub(crate) extern "C" fn ChannelMonitor_clone_void(this_ptr: *const c_void) -> *mut c_void {
919 Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChannelMonitor)).clone() })) as *mut c_void
922 /// Creates a copy of the ChannelMonitor
923 pub extern "C" fn ChannelMonitor_clone(orig: &ChannelMonitor) -> ChannelMonitor {
927 /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read
928 pub extern "C" fn ChannelMonitor_write(obj: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
929 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
932 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
933 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
935 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
938 /// panics if the given update is not the next update by update_id.
941 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &crate::lightning::chain::channelmonitor::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 {
942 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_monitor(updates.get_native_ref(), broadcaster, fee_estimator, logger);
943 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() };
947 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
951 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> u64 {
952 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_update_id();
956 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
959 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointCVec_u8ZZ {
960 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_funding_txo();
961 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();
965 /// Gets a list of txids, with their output scripts (in the order they appear in the
966 /// transaction), which we must learn about spends of via block_connected().
969 pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_ThirtyTwoBytesCVec_C2Tuple_u32CVec_u8ZZZZZ {
970 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_outputs_to_watch();
971 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 }); };
975 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
976 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
977 /// have been registered.
979 pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, filter: &crate::lightning::chain::Filter) {
980 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.load_outputs_to_watch(filter)
983 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
984 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
987 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
988 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_monitor_events();
989 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
993 /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
995 /// For channels featuring anchor outputs, this method will also process [`BumpTransaction`]
996 /// events produced from each [`ChannelMonitor`] while there is a balance to claim onchain
997 /// within each channel. As the confirmation of a commitment transaction may be critical to the
998 /// safety of funds, we recommend invoking this every 30 seconds, or lower if running in an
999 /// environment with spotty connections, like on mobile.
1001 /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
1002 /// order to handle these events.
1004 /// [`SpendableOutputs`]: crate::events::Event::SpendableOutputs
1005 /// [`BumpTransaction`]: crate::events::Event::BumpTransaction
1007 pub extern "C" fn ChannelMonitor_process_pending_events(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, handler: &crate::lightning::events::EventHandler) {
1008 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_pending_events(handler)
1011 /// Gets the counterparty's initial commitment transaction. The returned commitment
1012 /// transaction is unsigned. This is intended to be called during the initial persistence of
1013 /// the monitor (inside an implementation of [`Persist::persist_new_channel`]), to allow for
1014 /// watchtowers in the persistence pipeline to have enough data to form justice transactions.
1016 /// This is similar to [`Self::counterparty_commitment_txs_from_update`], except
1017 /// that for the initial commitment transaction, we don't have a corresponding update.
1019 /// This will only return `Some` for channel monitors that have been created after upgrading
1020 /// to LDK 0.0.117+.
1022 /// [`Persist::persist_new_channel`]: crate::chain::chainmonitor::Persist::persist_new_channel
1024 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
1027 pub extern "C" fn ChannelMonitor_initial_counterparty_commitment_tx(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::lightning::ln::chan_utils::CommitmentTransaction {
1028 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.initial_counterparty_commitment_tx();
1029 let mut local_ret = crate::lightning::ln::chan_utils::CommitmentTransaction { inner: if ret.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true };
1033 /// Gets all of the counterparty commitment transactions provided by the given update. This
1034 /// may be empty if the update doesn't include any new counterparty commitments. Returned
1035 /// commitment transactions are unsigned.
1037 /// This is provided so that watchtower clients in the persistence pipeline are able to build
1038 /// justice transactions for each counterparty commitment upon each update. It's intended to be
1039 /// used within an implementation of [`Persist::update_persisted_channel`], which is provided
1040 /// with a monitor and an update. Once revoked, signing a justice transaction can be done using
1041 /// [`Self::sign_to_local_justice_tx`].
1043 /// It is expected that a watchtower client may use this method to retrieve the latest counterparty
1044 /// commitment transaction(s), and then hold the necessary data until a later update in which
1045 /// the monitor has been updated with the corresponding revocation data, at which point the
1046 /// monitor can sign the justice transaction.
1048 /// This will only return a non-empty list for monitor updates that have been created after
1049 /// upgrading to LDK 0.0.117+. Note that no restriction lies on the monitors themselves, which
1050 /// may have been created prior to upgrading.
1052 /// [`Persist::update_persisted_channel`]: crate::chain::chainmonitor::Persist::update_persisted_channel
1055 pub extern "C" fn ChannelMonitor_counterparty_commitment_txs_from_update(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CVec_CommitmentTransactionZ {
1056 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.counterparty_commitment_txs_from_update(update.get_native_ref());
1057 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::chan_utils::CommitmentTransaction { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
1061 /// Wrapper around [`EcdsaChannelSigner::sign_justice_revoked_output`] to make
1062 /// signing the justice transaction easier for implementors of
1063 /// [`chain::chainmonitor::Persist`]. On success this method returns the provided transaction
1064 /// signing the input at `input_idx`. This method will only produce a valid signature for
1065 /// a transaction spending the `to_local` output of a commitment transaction, i.e. this cannot
1066 /// be used for revoked HTLC outputs.
1068 /// `Value` is the value of the output being spent by the input at `input_idx`, committed
1069 /// in the BIP 143 signature.
1071 /// This method will only succeed if this monitor has received the revocation secret for the
1072 /// provided `commitment_number`. If a commitment number is provided that does not correspond
1073 /// to the commitment transaction being revoked, this will return a signed transaction, but
1074 /// the signature will not be valid.
1076 /// [`EcdsaChannelSigner::sign_justice_revoked_output`]: crate::sign::EcdsaChannelSigner::sign_justice_revoked_output
1077 /// [`Persist`]: crate::chain::chainmonitor::Persist
1080 pub extern "C" fn ChannelMonitor_sign_to_local_justice_tx(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, mut justice_tx: crate::c_types::Transaction, mut input_idx: usize, mut value: u64, mut commitment_number: u64) -> crate::c_types::derived::CResult_TransactionNoneZ {
1081 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.sign_to_local_justice_tx(justice_tx.into_bitcoin(), input_idx, value, commitment_number);
1082 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() };
1086 /// Gets the `node_id` of the counterparty for this channel.
1088 /// Will be `None` for channels constructed on LDK versions prior to 0.0.110 and always `Some`
1091 /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None
1094 pub extern "C" fn ChannelMonitor_get_counterparty_node_id(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::PublicKey {
1095 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_counterparty_node_id();
1096 let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } };
1100 /// Used by [`ChannelManager`] deserialization to broadcast the latest holder state if its copy
1101 /// of the channel state was out-of-date.
1103 /// You may also use this to broadcast the latest local commitment transaction, either because
1104 /// a monitor update failed or because we've fallen behind (i.e. we've received proof that our
1105 /// counterparty side knows a revocation secret we gave them that they shouldn't know).
1107 /// Broadcasting these transactions in the second case is UNSAFE, as they allow counterparty
1108 /// side to punish you. Nevertheless you may want to broadcast them if counterparty doesn't
1109 /// close channel with their commitment transaction after a substantial amount of time. Best
1110 /// may be to contact the other node operator out-of-band to coordinate other options available
1113 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
1116 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
1117 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_holder_commitment_txn(logger);
1118 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::Transaction::from_bitcoin(&item) }); };
1122 /// Processes transactions in a newly connected block, which may result in any of the following:
1123 /// - update the monitor's state against resolved HTLCs
1124 /// - punish the counterparty in the case of seeing a revoked commitment transaction
1125 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
1126 /// - detect settled outputs for later spending
1127 /// - schedule and bump any in-flight claims
1129 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
1130 /// [`get_outputs_to_watch`].
1132 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
1135 pub extern "C" fn ChannelMonitor_block_connected(this_arg: &crate::lightning::chain::channelmonitor::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 {
1136 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 }); };
1137 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::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
1138 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 }); };
1142 /// Determines if the disconnected block contained any transactions of interest and updates
1145 pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &crate::lightning::chain::channelmonitor::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) {
1146 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
1149 /// Processes transactions confirmed in a block with the given header and height, returning new
1150 /// outputs to watch. See [`block_connected`] for details.
1152 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1153 /// blocks. See [`chain::Confirm`] for calling expectations.
1155 /// [`block_connected`]: Self::block_connected
1158 pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &crate::lightning::chain::channelmonitor::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 {
1159 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 }); };
1160 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::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
1161 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 }); };
1165 /// Processes a transaction that was reorganized out of the chain.
1167 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
1168 /// than blocks. See [`chain::Confirm`] for calling expectations.
1170 /// [`block_disconnected`]: Self::block_disconnected
1172 pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &crate::lightning::chain::channelmonitor::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) {
1173 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger)
1176 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
1177 /// [`block_connected`] for details.
1179 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
1180 /// blocks. See [`chain::Confirm`] for calling expectations.
1182 /// [`block_connected`]: Self::block_connected
1185 pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &crate::lightning::chain::channelmonitor::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 {
1186 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);
1187 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 }); };
1191 /// Returns the set of txids that should be monitored for re-organization out of the chain.
1194 pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_ThirtyTwoBytesCOption_ThirtyTwoBytesZZZ {
1195 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_relevant_txids();
1196 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 = if orig_ret_0_1.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.unwrap().into_inner() } }) }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1).into(); local_ret_0 }); };
1200 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
1201 /// [`chain::Confirm`] interfaces.
1204 pub extern "C" fn ChannelMonitor_current_best_block(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::lightning::chain::BestBlock {
1205 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
1206 crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
1209 /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
1210 /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
1211 /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
1212 /// invoking this every 30 seconds, or lower if running in an environment with spotty
1213 /// connections, like on mobile.
1215 pub extern "C" fn ChannelMonitor_rebroadcast_pending_claims(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) {
1216 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.rebroadcast_pending_claims(broadcaster, fee_estimator, logger)
1219 /// Returns the descriptors for relevant outputs (i.e., those that we can spend) within the
1220 /// transaction if they exist and the transaction has at least [`ANTI_REORG_DELAY`]
1221 /// confirmations. For [`SpendableOutputDescriptor::DelayedPaymentOutput`] descriptors to be
1222 /// returned, the transaction must have at least `max(ANTI_REORG_DELAY, to_self_delay)`
1225 /// Descriptors returned by this method are primarily exposed via [`Event::SpendableOutputs`]
1226 /// once they are no longer under reorg risk. This method serves as a way to retrieve these
1227 /// descriptors at a later time, either for historical purposes, or to replay any
1228 /// missed/unhandled descriptors. For the purpose of gathering historical records, if the
1229 /// channel close has fully resolved (i.e., [`ChannelMonitor::get_claimable_balances`] returns
1230 /// an empty set), you can retrieve all spendable outputs by providing all descendant spending
1231 /// transactions starting from the channel's funding transaction and going down three levels.
1233 /// `tx` is a transaction we'll scan the outputs of. Any transaction can be provided. If any
1234 /// outputs which can be spent by us are found, at least one descriptor is returned.
1236 /// `confirmation_height` must be the height of the block in which `tx` was included in.
1239 pub extern "C" fn ChannelMonitor_get_spendable_outputs(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor, mut tx: crate::c_types::Transaction, mut confirmation_height: u32) -> crate::c_types::derived::CVec_SpendableOutputDescriptorZ {
1240 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_spendable_outputs(&tx.into_bitcoin(), confirmation_height);
1241 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::sign::SpendableOutputDescriptor::native_into(item) }); };
1245 /// Gets the balances in this channel which are either claimable by us if we were to
1246 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1249 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1250 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1251 /// balance, or until our counterparty has claimed the balance and accrued several
1252 /// confirmations on the claim transaction.
1254 /// Note that for `ChannelMonitors` which track a channel which went on-chain with versions of
1255 /// LDK prior to 0.0.111, not all or excess balances may be included.
1257 /// See [`Balance`] for additional details on the types of claimable balances which
1258 /// may be returned here and their meanings.
1261 pub extern "C" fn ChannelMonitor_get_claimable_balances(this_arg: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CVec_BalanceZ {
1262 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_claimable_balances();
1263 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::Balance::native_into(item) }); };
1268 /// Read a C2Tuple_ThirtyTwoBytesChannelMonitorZ from a byte array, created by C2Tuple_ThirtyTwoBytesChannelMonitorZ_write
1269 pub extern "C" fn C2Tuple_ThirtyTwoBytesChannelMonitorZ_read(ser: crate::c_types::u8slice, arg_a: &crate::lightning::sign::EntropySource, arg_b: &crate::lightning::sign::SignerProvider) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ {
1270 let arg_a_conv = arg_a;
1271 let arg_b_conv = arg_b;
1272 let arg_conv = (arg_a_conv, arg_b_conv);
1273 let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::WriteableEcdsaChannelSigner>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1274 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::native_into(e) }).into() };