1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see [`chain::Watch`] for more.
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
14 //! [`chain::Watch`]: ../trait.Watch.html
17 use bitcoin::hashes::Hash;
18 use crate::c_types::*;
21 use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport;
22 type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport;
24 /// An update generated by the underlying Channel itself which contains some new information the
25 /// ChannelMonitor should be made aware of.
28 pub struct ChannelMonitorUpdate {
29 /// A pointer to the opaque Rust object.
31 /// Nearly everywhere, inner must be non-null, however in places where
32 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
33 pub inner: *mut nativeChannelMonitorUpdate,
34 /// Indicates that this is the only struct which contains the same pointer.
36 /// Rust functions which take ownership of an object provided via an argument require
37 /// this to be true and invalidate the object pointed to by inner.
41 impl Drop for ChannelMonitorUpdate {
43 if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
44 let _ = unsafe { Box::from_raw(self.inner) };
48 /// Frees any resources used by the ChannelMonitorUpdate, if is_owned is set and inner is non-NULL.
50 pub extern "C" fn ChannelMonitorUpdate_free(this_obj: ChannelMonitorUpdate) { }
52 /// Used only if an object of this type is returned as a trait impl by a method
53 extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
54 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); }
57 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
58 impl ChannelMonitorUpdate {
59 pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
60 assert!(self.is_owned);
62 self.inner = std::ptr::null_mut();
66 /// The sequence number of this update. Updates *must* be replayed in-order according to this
67 /// sequence number (and updates may panic if they are not). The update_id values are strictly
68 /// increasing and increase by one for each new update, with one exception specified below.
70 /// This sequence number is also used to track up to which points updates which returned
71 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
72 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
74 /// The only instance where update_id values are not strictly increasing is the case where we
75 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
76 /// its docs for more details.
78 /// [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
80 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
81 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_id;
84 /// The sequence number of this update. Updates *must* be replayed in-order according to this
85 /// sequence number (and updates may panic if they are not). The update_id values are strictly
86 /// increasing and increase by one for each new update, with one exception specified below.
88 /// This sequence number is also used to track up to which points updates which returned
89 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
90 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
92 /// The only instance where update_id values are not strictly increasing is the case where we
93 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
94 /// its docs for more details.
96 /// [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
98 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
99 unsafe { &mut *this_ptr.inner }.update_id = val;
101 impl Clone for ChannelMonitorUpdate {
102 fn clone(&self) -> Self {
104 inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
105 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
111 /// Used only if an object of this type is returned as a trait impl by a method
112 pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
113 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
116 /// Creates a copy of the ChannelMonitorUpdate
117 pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
121 /// (1) a channel has been force closed and
122 /// (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
123 /// this channel's (the backward link's) broadcasted commitment transaction
124 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
125 /// with the update providing said payment preimage. No other update types are allowed after
129 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
131 /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read
132 pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
133 crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
136 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
137 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
140 /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write
141 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
142 let res = crate::c_types::deserialize_obj(ser);
143 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
146 /// An error enum representing a failure to persist a channel monitor update.
150 pub enum ChannelMonitorUpdateErr {
151 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
152 /// our state failed, but is expected to succeed at some point in the future).
154 /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
155 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
156 /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
157 /// restore the channel to an operational state.
159 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
160 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
161 /// writing out the latest ChannelManager state.
163 /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
164 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
165 /// to claim it on this channel) and those updates must be applied wherever they can be. At
166 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
167 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
168 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
171 /// Note that even if updates made after TemporaryFailure succeed you must still call
172 /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
175 /// Note that the update being processed here will not be replayed for you when you call
176 /// ChannelManager::channel_monitor_updated, so you must store the update itself along
177 /// with the persisted ChannelMonitor on your own local disk prior to returning a
178 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
179 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
182 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
183 /// remote location (with local copies persisted immediately), it is anticipated that all
184 /// updates will return TemporaryFailure until the remote copies could be updated.
186 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
187 /// different watchtower and cannot update with all watchtowers that were previously informed
188 /// of this channel).
190 /// At reception of this error, ChannelManager will force-close the channel and return at
191 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
192 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
193 /// update must be rejected.
195 /// This failure may also signal a failure to update the local persisted copy of one of
196 /// the channel monitor instance.
198 /// Note that even when you fail a holder commitment transaction update, you must store the
199 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
200 /// broadcasts it (e.g distributed channel-monitor deployment)
202 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
203 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
204 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
205 /// lagging behind on block processing.
208 use lightning::chain::channelmonitor::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
209 impl ChannelMonitorUpdateErr {
211 pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
213 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
214 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
218 pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
220 ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
221 ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
225 pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
227 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
228 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
232 pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
234 nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
235 nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
239 /// Creates a copy of the ChannelMonitorUpdateErr
241 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
245 use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport;
246 type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport;
248 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
249 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
250 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
252 /// Contains a developer-readable error message.
255 pub struct MonitorUpdateError {
256 /// A pointer to the opaque Rust object.
258 /// Nearly everywhere, inner must be non-null, however in places where
259 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
260 pub inner: *mut nativeMonitorUpdateError,
261 /// Indicates that this is the only struct which contains the same pointer.
263 /// Rust functions which take ownership of an object provided via an argument require
264 /// this to be true and invalidate the object pointed to by inner.
268 impl Drop for MonitorUpdateError {
270 if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) {
271 let _ = unsafe { Box::from_raw(self.inner) };
275 /// Frees any resources used by the MonitorUpdateError, if is_owned is set and inner is non-NULL.
277 pub extern "C" fn MonitorUpdateError_free(this_obj: MonitorUpdateError) { }
279 /// Used only if an object of this type is returned as a trait impl by a method
280 extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
281 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); }
284 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
285 impl MonitorUpdateError {
286 pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
287 assert!(self.is_owned);
288 let ret = self.inner;
289 self.inner = std::ptr::null_mut();
293 impl Clone for MonitorUpdateError {
294 fn clone(&self) -> Self {
296 inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else {
297 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
303 /// Used only if an object of this type is returned as a trait impl by a method
304 pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void {
305 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void
308 /// Creates a copy of the MonitorUpdateError
309 pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError {
312 /// An event to be processed by the ChannelManager.
316 pub enum MonitorEvent {
317 /// A monitor event containing an HTLCUpdate.
318 HTLCEvent(crate::chain::channelmonitor::HTLCUpdate),
319 /// A monitor event that the Channel's commitment transaction was broadcasted.
320 CommitmentTxBroadcasted(crate::chain::transaction::OutPoint),
322 use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent;
325 pub(crate) fn to_native(&self) -> nativeMonitorEvent {
327 MonitorEvent::HTLCEvent (ref a, ) => {
328 let mut a_nonref = (*a).clone();
329 nativeMonitorEvent::HTLCEvent (
330 *unsafe { Box::from_raw(a_nonref.take_inner()) },
333 MonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
334 let mut a_nonref = (*a).clone();
335 nativeMonitorEvent::CommitmentTxBroadcasted (
336 *unsafe { Box::from_raw(a_nonref.take_inner()) },
342 pub(crate) fn into_native(self) -> nativeMonitorEvent {
344 MonitorEvent::HTLCEvent (mut a, ) => {
345 nativeMonitorEvent::HTLCEvent (
346 *unsafe { Box::from_raw(a.take_inner()) },
349 MonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
350 nativeMonitorEvent::CommitmentTxBroadcasted (
351 *unsafe { Box::from_raw(a.take_inner()) },
357 pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
359 nativeMonitorEvent::HTLCEvent (ref a, ) => {
360 let mut a_nonref = (*a).clone();
361 MonitorEvent::HTLCEvent (
362 crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
365 nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
366 let mut a_nonref = (*a).clone();
367 MonitorEvent::CommitmentTxBroadcasted (
368 crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
374 pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
376 nativeMonitorEvent::HTLCEvent (mut a, ) => {
377 MonitorEvent::HTLCEvent (
378 crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true },
381 nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
382 MonitorEvent::CommitmentTxBroadcasted (
383 crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true },
389 /// Frees any resources used by the MonitorEvent
391 pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
392 /// Creates a copy of the MonitorEvent
394 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
398 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
399 type nativeHTLCUpdate = nativeHTLCUpdateImport;
401 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
402 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
403 /// preimage claim backward will lead to loss of funds.
405 /// [`chain::Watch`]: ../trait.Watch.html
408 pub struct HTLCUpdate {
409 /// A pointer to the opaque Rust object.
411 /// Nearly everywhere, inner must be non-null, however in places where
412 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
413 pub inner: *mut nativeHTLCUpdate,
414 /// Indicates that this is the only struct which contains the same pointer.
416 /// Rust functions which take ownership of an object provided via an argument require
417 /// this to be true and invalidate the object pointed to by inner.
421 impl Drop for HTLCUpdate {
423 if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
424 let _ = unsafe { Box::from_raw(self.inner) };
428 /// Frees any resources used by the HTLCUpdate, if is_owned is set and inner is non-NULL.
430 pub extern "C" fn HTLCUpdate_free(this_obj: HTLCUpdate) { }
432 /// Used only if an object of this type is returned as a trait impl by a method
433 extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
434 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); }
437 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
439 pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
440 assert!(self.is_owned);
441 let ret = self.inner;
442 self.inner = std::ptr::null_mut();
446 impl Clone for HTLCUpdate {
447 fn clone(&self) -> Self {
449 inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
450 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
456 /// Used only if an object of this type is returned as a trait impl by a method
457 pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
458 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCUpdate)).clone() })) as *mut c_void
461 /// Creates a copy of the HTLCUpdate
462 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
466 /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read
467 pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
468 crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
471 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
472 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
475 /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write
476 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
477 let res = crate::c_types::deserialize_obj(ser);
478 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
482 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
483 type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::Sign>;
485 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
486 /// on-chain transactions to ensure no loss of funds occurs.
488 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
489 /// information and are actively monitoring the chain.
491 /// Pending Events or updated HTLCs which have not yet been read out by
492 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
493 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
494 /// gotten are fully handled before re-serializing the new state.
496 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
497 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
498 /// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
499 /// returned block hash and the the current chain and then reconnecting blocks to get to the
500 /// best chain) upon deserializing the object!
503 pub struct ChannelMonitor {
504 /// A pointer to the opaque Rust object.
506 /// Nearly everywhere, inner must be non-null, however in places where
507 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
508 pub inner: *mut nativeChannelMonitor,
509 /// Indicates that this is the only struct which contains the same pointer.
511 /// Rust functions which take ownership of an object provided via an argument require
512 /// this to be true and invalidate the object pointed to by inner.
516 impl Drop for ChannelMonitor {
518 if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
519 let _ = unsafe { Box::from_raw(self.inner) };
523 /// Frees any resources used by the ChannelMonitor, if is_owned is set and inner is non-NULL.
525 pub extern "C" fn ChannelMonitor_free(this_obj: ChannelMonitor) { }
527 /// Used only if an object of this type is returned as a trait impl by a method
528 extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
529 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); }
532 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
533 impl ChannelMonitor {
534 pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
535 assert!(self.is_owned);
536 let ret = self.inner;
537 self.inner = std::ptr::null_mut();
542 /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read
543 pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
544 crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
547 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
548 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
550 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
553 /// panics if the given update is not the next update by update_id.
556 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::chain::chaininterface::FeeEstimator, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ {
557 let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger);
558 let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
562 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
566 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 {
567 let mut ret = unsafe { &*this_arg.inner }.get_latest_update_id();
571 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
574 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ {
575 let mut ret = unsafe { &*this_arg.inner }.get_funding_txo();
576 let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, orig_ret_1.into_bytes().into()).into();
580 /// Gets a list of txids, with their output scripts (in the order they appear in the
581 /// transaction), which we must learn about spends of via block_connected().
584 pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ {
585 let mut ret = unsafe { &*this_arg.inner }.get_outputs_to_watch();
586 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 }); };
590 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
591 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
592 /// have been registered.
594 pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor, filter: &crate::chain::Filter) {
595 unsafe { &*this_arg.inner }.load_outputs_to_watch(filter)
598 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
599 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
601 /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
604 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
605 let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_monitor_events();
606 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent::native_into(item) }); };
610 /// Gets the list of pending events which were generated by previous actions, clearing the list
613 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
614 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
615 /// no internal locking in ChannelMonitors.
618 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
619 let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_events();
620 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
624 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
625 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
626 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
627 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
628 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
629 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
630 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
631 /// out-of-band the other node operator to coordinate with him if option is available to you.
632 /// In any-case, choice is up to the user.
635 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &ChannelMonitor, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
636 let mut ret = unsafe { &*this_arg.inner }.get_latest_holder_commitment_txn(logger);
637 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let mut local_ret_0 = ::bitcoin::consensus::encode::serialize(&item); crate::c_types::Transaction::from_vec(local_ret_0) }); };
641 /// Processes transactions in a newly connected block, which may result in any of the following:
642 /// - update the monitor's state against resolved HTLCs
643 /// - punish the counterparty in the case of seeing a revoked commitment transaction
644 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
645 /// - detect settled outputs for later spending
646 /// - schedule and bump any in-flight claims
648 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
649 /// [`get_outputs_to_watch`].
651 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
654 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::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut logger: crate::util::logger::Logger) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
655 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 }); };
656 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::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
657 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 }); };
661 /// Determines if the disconnected block contained any transactions of interest and updates
664 pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut logger: crate::util::logger::Logger) {
665 unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
668 /// `Persist` defines behavior for persisting channel monitors: this could mean
669 /// writing once to disk, and/or uploading to one or more backup services.
671 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
672 /// to disk/backups. And, on every update, you **must** persist either the
673 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
674 /// of situations such as revoking a transaction, then crashing before this
675 /// revocation can be persisted, then unintentionally broadcasting a revoked
676 /// transaction and losing money. This is a risk because previous channel states
677 /// are toxic, so it's important that whatever channel state is persisted is
681 /// An opaque pointer which is passed to your function implementations as an argument.
682 /// This has no meaning in the LDK, and can be NULL or any other value.
683 pub this_arg: *mut c_void,
684 /// Persist a new channel's data. The data can be stored any way you want, but
685 /// the identifier provided by Rust-Lightning is the channel's outpoint (and
686 /// it is up to you to maintain a correct mapping between the outpoint and the
687 /// stored channel data). Note that you **must** persist every new monitor to
688 /// disk. See the `Persist` trait documentation for more details.
690 /// See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
691 /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
693 /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
694 /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
696 pub persist_new_channel: extern "C" fn (this_arg: *const c_void, id: crate::chain::transaction::OutPoint, data: &crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
697 /// Update one channel's data. The provided `ChannelMonitor` has already
698 /// applied the given update.
700 /// Note that on every update, you **must** persist either the
701 /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
702 /// the `Persist` trait documentation for more details.
704 /// If an implementer chooses to persist the updates only, they need to make
705 /// sure that all the updates are applied to the `ChannelMonitors` *before*
706 /// the set of channel monitors is given to the `ChannelManager`
707 /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
708 /// applying a monitor update to a monitor. If full `ChannelMonitors` are
709 /// persisted, then there is no need to persist individual updates.
711 /// Note that there could be a performance tradeoff between persisting complete
712 /// channel monitors on every update vs. persisting only updates and applying
713 /// them in batches. The size of each monitor grows `O(number of state updates)`
714 /// whereas updates are small and `O(1)`.
716 /// See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
717 /// [`ChannelMonitorUpdate::write`] for writing out an update, and
718 /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
720 /// [`ChannelMonitor::update_monitor`]: struct.ChannelMonitor.html#impl-1
721 /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
722 /// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
723 /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
725 pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, id: crate::chain::transaction::OutPoint, update: &crate::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
726 /// Frees any resources associated with this object given its this_arg pointer.
727 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
728 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
730 unsafe impl Send for Persist {}
731 unsafe impl Sync for Persist {}
733 use lightning::chain::channelmonitor::Persist as rustPersist;
734 impl rustPersist<crate::chain::keysinterface::Sign> for Persist {
735 fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
736 let mut ret = (self.persist_new_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
737 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() })};
740 fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
741 let mut ret = (self.update_persisted_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
742 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() })};
747 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
748 // directly as a Deref trait in higher-level structs:
749 impl std::ops::Deref for Persist {
751 fn deref(&self) -> &Self {
755 /// Calls the free function if one is set
757 pub extern "C" fn Persist_free(this_ptr: Persist) { }
758 impl Drop for Persist {
760 if let Some(f) = self.free {
766 /// Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write
767 pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
769 let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
770 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::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::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };