Merge pull request #45 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / lightning / chain / channelmonitor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
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.
8
9 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
10 //! here.
11 //!
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.
15 //!
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.
21
22 use std::str::FromStr;
23 use std::ffi::c_void;
24 use core::convert::Infallible;
25 use bitcoin::hashes::Hash;
26 use crate::c_types::*;
27
28
29 use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport;
30 type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport;
31
32 /// An update generated by the underlying Channel itself which contains some new information the
33 /// ChannelMonitor should be made aware of.
34 #[must_use]
35 #[repr(C)]
36 pub struct ChannelMonitorUpdate {
37         /// A pointer to the opaque Rust object.
38
39         /// Nearly everywhere, inner must be non-null, however in places where
40         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
41         pub inner: *mut nativeChannelMonitorUpdate,
42         /// Indicates that this is the only struct which contains the same pointer.
43
44         /// Rust functions which take ownership of an object provided via an argument require
45         /// this to be true and invalidate the object pointed to by inner.
46         pub is_owned: bool,
47 }
48
49 impl Drop for ChannelMonitorUpdate {
50         fn drop(&mut self) {
51                 if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
52                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
53                 }
54         }
55 }
56 /// Frees any resources used by the ChannelMonitorUpdate, if is_owned is set and inner is non-NULL.
57 #[no_mangle]
58 pub extern "C" fn ChannelMonitorUpdate_free(this_obj: ChannelMonitorUpdate) { }
59 #[allow(unused)]
60 /// Used only if an object of this type is returned as a trait impl by a method
61 extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
62         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); }
63 }
64 #[allow(unused)]
65 impl ChannelMonitorUpdate {
66         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitorUpdate {
67                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
68         }
69         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitorUpdate {
70                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
71         }
72         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
73         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
74                 assert!(self.is_owned);
75                 let ret = ObjOps::untweak_ptr(self.inner);
76                 self.inner = std::ptr::null_mut();
77                 ret
78         }
79 }
80 /// The sequence number of this update. Updates *must* be replayed in-order according to this
81 /// sequence number (and updates may panic if they are not). The update_id values are strictly
82 /// increasing and increase by one for each new update, with one exception specified below.
83 ///
84 /// This sequence number is also used to track up to which points updates which returned
85 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
86 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
87 ///
88 /// The only instance where update_id values are not strictly increasing is the case where we
89 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
90 /// its docs for more details.
91 #[no_mangle]
92 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
93         let mut inner_val = &mut this_ptr.get_native_mut_ref().update_id;
94         *inner_val
95 }
96 /// The sequence number of this update. Updates *must* be replayed in-order according to this
97 /// sequence number (and updates may panic if they are not). The update_id values are strictly
98 /// increasing and increase by one for each new update, with one exception specified below.
99 ///
100 /// This sequence number is also used to track up to which points updates which returned
101 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
102 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
103 ///
104 /// The only instance where update_id values are not strictly increasing is the case where we
105 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
106 /// its docs for more details.
107 #[no_mangle]
108 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
109         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_id = val;
110 }
111 impl Clone for ChannelMonitorUpdate {
112         fn clone(&self) -> Self {
113                 Self {
114                         inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
115                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
116                         is_owned: true,
117                 }
118         }
119 }
120 #[allow(unused)]
121 /// Used only if an object of this type is returned as a trait impl by a method
122 pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
123         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
124 }
125 #[no_mangle]
126 /// Creates a copy of the ChannelMonitorUpdate
127 pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
128         orig.clone()
129 }
130 /// If:
131 ///    (1) a channel has been force closed and
132 ///    (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
133 ///        this channel's (the backward link's) broadcasted commitment transaction
134 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
135 /// with the update providing said payment preimage. No other update types are allowed after
136 /// force-close.
137
138 #[no_mangle]
139 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
140 #[no_mangle]
141 /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read
142 pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
143         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
144 }
145 #[no_mangle]
146 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
147         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
148 }
149 #[no_mangle]
150 /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write
151 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
152         let res = crate::c_types::deserialize_obj(ser);
153         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
154         local_res
155 }
156 /// An error enum representing a failure to persist a channel monitor update.
157 #[must_use]
158 #[derive(Clone)]
159 #[repr(C)]
160 pub enum ChannelMonitorUpdateErr {
161         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
162         /// our state failed, but is expected to succeed at some point in the future).
163         ///
164         /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
165         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
166         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
167         /// restore the channel to an operational state.
168         ///
169         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
170         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
171         /// writing out the latest ChannelManager state.
172         ///
173         /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
174         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
175         /// to claim it on this channel) and those updates must be applied wherever they can be. At
176         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
177         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
178         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
179         /// been \"frozen\".
180         ///
181         /// Note that even if updates made after TemporaryFailure succeed you must still call
182         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
183         /// operation.
184         ///
185         /// Note that the update being processed here will not be replayed for you when you call
186         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
187         /// with the persisted ChannelMonitor on your own local disk prior to returning a
188         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
189         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
190         /// reload-time.
191         ///
192         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
193         /// remote location (with local copies persisted immediately), it is anticipated that all
194         /// updates will return TemporaryFailure until the remote copies could be updated.
195         TemporaryFailure,
196         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
197         /// different watchtower and cannot update with all watchtowers that were previously informed
198         /// of this channel).
199         ///
200         /// At reception of this error, ChannelManager will force-close the channel and return at
201         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
202         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
203         /// update must be rejected.
204         ///
205         /// This failure may also signal a failure to update the local persisted copy of one of
206         /// the channel monitor instance.
207         ///
208         /// Note that even when you fail a holder commitment transaction update, you must store the
209         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
210         /// broadcasts it (e.g distributed channel-monitor deployment)
211         ///
212         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
213         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
214         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
215         /// lagging behind on block processing.
216         PermanentFailure,
217 }
218 use lightning::chain::channelmonitor::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
219 impl ChannelMonitorUpdateErr {
220         #[allow(unused)]
221         pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
222                 match self {
223                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
224                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
225                 }
226         }
227         #[allow(unused)]
228         pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
229                 match self {
230                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
231                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
232                 }
233         }
234         #[allow(unused)]
235         pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
236                 match native {
237                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
238                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
239                 }
240         }
241         #[allow(unused)]
242         pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
243                 match native {
244                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
245                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
246                 }
247         }
248 }
249 /// Creates a copy of the ChannelMonitorUpdateErr
250 #[no_mangle]
251 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
252         orig.clone()
253 }
254 #[no_mangle]
255 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
256 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
257         ChannelMonitorUpdateErr::TemporaryFailure}
258 #[no_mangle]
259 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
260 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
261         ChannelMonitorUpdateErr::PermanentFailure}
262
263 use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport;
264 type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport;
265
266 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
267 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
268 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
269 /// corrupted.
270 /// Contains a developer-readable error message.
271 #[must_use]
272 #[repr(C)]
273 pub struct MonitorUpdateError {
274         /// A pointer to the opaque Rust object.
275
276         /// Nearly everywhere, inner must be non-null, however in places where
277         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
278         pub inner: *mut nativeMonitorUpdateError,
279         /// Indicates that this is the only struct which contains the same pointer.
280
281         /// Rust functions which take ownership of an object provided via an argument require
282         /// this to be true and invalidate the object pointed to by inner.
283         pub is_owned: bool,
284 }
285
286 impl Drop for MonitorUpdateError {
287         fn drop(&mut self) {
288                 if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) {
289                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
290                 }
291         }
292 }
293 /// Frees any resources used by the MonitorUpdateError, if is_owned is set and inner is non-NULL.
294 #[no_mangle]
295 pub extern "C" fn MonitorUpdateError_free(this_obj: MonitorUpdateError) { }
296 #[allow(unused)]
297 /// Used only if an object of this type is returned as a trait impl by a method
298 extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
299         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); }
300 }
301 #[allow(unused)]
302 impl MonitorUpdateError {
303         pub(crate) fn get_native_ref(&self) -> &'static nativeMonitorUpdateError {
304                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
305         }
306         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMonitorUpdateError {
307                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
308         }
309         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
310         pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
311                 assert!(self.is_owned);
312                 let ret = ObjOps::untweak_ptr(self.inner);
313                 self.inner = std::ptr::null_mut();
314                 ret
315         }
316 }
317 impl Clone for MonitorUpdateError {
318         fn clone(&self) -> Self {
319                 Self {
320                         inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else {
321                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
322                         is_owned: true,
323                 }
324         }
325 }
326 #[allow(unused)]
327 /// Used only if an object of this type is returned as a trait impl by a method
328 pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void {
329         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void
330 }
331 #[no_mangle]
332 /// Creates a copy of the MonitorUpdateError
333 pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError {
334         orig.clone()
335 }
336 /// An event to be processed by the ChannelManager.
337 #[must_use]
338 #[derive(Clone)]
339 #[repr(C)]
340 pub enum MonitorEvent {
341         /// A monitor event containing an HTLCUpdate.
342         HTLCEvent(crate::lightning::chain::channelmonitor::HTLCUpdate),
343         /// A monitor event that the Channel's commitment transaction was confirmed.
344         CommitmentTxConfirmed(crate::lightning::chain::transaction::OutPoint),
345 }
346 use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent;
347 impl MonitorEvent {
348         #[allow(unused)]
349         pub(crate) fn to_native(&self) -> nativeMonitorEvent {
350                 match self {
351                         MonitorEvent::HTLCEvent (ref a, ) => {
352                                 let mut a_nonref = (*a).clone();
353                                 nativeMonitorEvent::HTLCEvent (
354                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
355                                 )
356                         },
357                         MonitorEvent::CommitmentTxConfirmed (ref a, ) => {
358                                 let mut a_nonref = (*a).clone();
359                                 nativeMonitorEvent::CommitmentTxConfirmed (
360                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
361                                 )
362                         },
363                 }
364         }
365         #[allow(unused)]
366         pub(crate) fn into_native(self) -> nativeMonitorEvent {
367                 match self {
368                         MonitorEvent::HTLCEvent (mut a, ) => {
369                                 nativeMonitorEvent::HTLCEvent (
370                                         *unsafe { Box::from_raw(a.take_inner()) },
371                                 )
372                         },
373                         MonitorEvent::CommitmentTxConfirmed (mut a, ) => {
374                                 nativeMonitorEvent::CommitmentTxConfirmed (
375                                         *unsafe { Box::from_raw(a.take_inner()) },
376                                 )
377                         },
378                 }
379         }
380         #[allow(unused)]
381         pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
382                 match native {
383                         nativeMonitorEvent::HTLCEvent (ref a, ) => {
384                                 let mut a_nonref = (*a).clone();
385                                 MonitorEvent::HTLCEvent (
386                                         crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
387                                 )
388                         },
389                         nativeMonitorEvent::CommitmentTxConfirmed (ref a, ) => {
390                                 let mut a_nonref = (*a).clone();
391                                 MonitorEvent::CommitmentTxConfirmed (
392                                         crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a_nonref), is_owned: true },
393                                 )
394                         },
395                 }
396         }
397         #[allow(unused)]
398         pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
399                 match native {
400                         nativeMonitorEvent::HTLCEvent (mut a, ) => {
401                                 MonitorEvent::HTLCEvent (
402                                         crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(a), is_owned: true },
403                                 )
404                         },
405                         nativeMonitorEvent::CommitmentTxConfirmed (mut a, ) => {
406                                 MonitorEvent::CommitmentTxConfirmed (
407                                         crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(a), is_owned: true },
408                                 )
409                         },
410                 }
411         }
412 }
413 /// Frees any resources used by the MonitorEvent
414 #[no_mangle]
415 pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
416 /// Creates a copy of the MonitorEvent
417 #[no_mangle]
418 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
419         orig.clone()
420 }
421 #[no_mangle]
422 /// Utility method to constructs a new HTLCEvent-variant MonitorEvent
423 pub extern "C" fn MonitorEvent_htlcevent(a: crate::lightning::chain::channelmonitor::HTLCUpdate) -> MonitorEvent {
424         MonitorEvent::HTLCEvent(a, )
425 }
426 #[no_mangle]
427 /// Utility method to constructs a new CommitmentTxConfirmed-variant MonitorEvent
428 pub extern "C" fn MonitorEvent_commitment_tx_confirmed(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent {
429         MonitorEvent::CommitmentTxConfirmed(a, )
430 }
431
432 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
433 type nativeHTLCUpdate = nativeHTLCUpdateImport;
434
435 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
436 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
437 /// preimage claim backward will lead to loss of funds.
438 #[must_use]
439 #[repr(C)]
440 pub struct HTLCUpdate {
441         /// A pointer to the opaque Rust object.
442
443         /// Nearly everywhere, inner must be non-null, however in places where
444         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
445         pub inner: *mut nativeHTLCUpdate,
446         /// Indicates that this is the only struct which contains the same pointer.
447
448         /// Rust functions which take ownership of an object provided via an argument require
449         /// this to be true and invalidate the object pointed to by inner.
450         pub is_owned: bool,
451 }
452
453 impl Drop for HTLCUpdate {
454         fn drop(&mut self) {
455                 if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
456                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
457                 }
458         }
459 }
460 /// Frees any resources used by the HTLCUpdate, if is_owned is set and inner is non-NULL.
461 #[no_mangle]
462 pub extern "C" fn HTLCUpdate_free(this_obj: HTLCUpdate) { }
463 #[allow(unused)]
464 /// Used only if an object of this type is returned as a trait impl by a method
465 extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
466         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); }
467 }
468 #[allow(unused)]
469 impl HTLCUpdate {
470         pub(crate) fn get_native_ref(&self) -> &'static nativeHTLCUpdate {
471                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
472         }
473         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeHTLCUpdate {
474                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
475         }
476         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
477         pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
478                 assert!(self.is_owned);
479                 let ret = ObjOps::untweak_ptr(self.inner);
480                 self.inner = std::ptr::null_mut();
481                 ret
482         }
483 }
484 impl Clone for HTLCUpdate {
485         fn clone(&self) -> Self {
486                 Self {
487                         inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
488                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
489                         is_owned: true,
490                 }
491         }
492 }
493 #[allow(unused)]
494 /// Used only if an object of this type is returned as a trait impl by a method
495 pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
496         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCUpdate)).clone() })) as *mut c_void
497 }
498 #[no_mangle]
499 /// Creates a copy of the HTLCUpdate
500 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
501         orig.clone()
502 }
503 #[no_mangle]
504 /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read
505 pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
506         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
507 }
508 #[no_mangle]
509 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
510         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
511 }
512 #[no_mangle]
513 /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write
514 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
515         let res = crate::c_types::deserialize_obj(ser);
516         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
517         local_res
518 }
519 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding
520 /// inbound HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us
521 /// losing money.
522 ///
523 /// Note that this is a library-wide security assumption. If a reorg deeper than this number of
524 /// blocks occurs, counterparties may be able to steal funds or claims made by and balances exposed
525 /// by a  [`ChannelMonitor`] may be incorrect.
526
527 #[no_mangle]
528 pub static ANTI_REORG_DELAY: u32 = lightning::chain::channelmonitor::ANTI_REORG_DELAY;
529 /// Details about the balance(s) available for spending once the channel appears on chain.
530 ///
531 /// See [`ChannelMonitor::get_claimable_balances`] for more details on when these will or will not
532 /// be provided.
533 #[must_use]
534 #[derive(Clone)]
535 #[repr(C)]
536 pub enum Balance {
537         /// The channel is not yet closed (or the commitment or closing transaction has not yet
538         /// appeared in a block). The given balance is claimable (less on-chain fees) if the channel is
539         /// force-closed now.
540         ClaimableOnChannelClose {
541                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
542                 /// required to do so.
543                 claimable_amount_satoshis: u64,
544         },
545         /// The channel has been closed, and the given balance is ours but awaiting confirmations until
546         /// we consider it spendable.
547         ClaimableAwaitingConfirmations {
548                 /// The amount available to claim, in satoshis, possibly excluding the on-chain fees which
549                 /// were spent in broadcasting the transaction.
550                 claimable_amount_satoshis: u64,
551                 /// The height at which an [`Event::SpendableOutputs`] event will be generated for this
552                 /// amount.
553                 confirmation_height: u32,
554         },
555         /// The channel has been closed, and the given balance should be ours but awaiting spending
556         /// transaction confirmation. If the spending transaction does not confirm in time, it is
557         /// possible our counterparty can take the funds by broadcasting an HTLC timeout on-chain.
558         ///
559         /// Once the spending transaction confirms, before it has reached enough confirmations to be
560         /// considered safe from chain reorganizations, the balance will instead be provided via
561         /// [`Balance::ClaimableAwaitingConfirmations`].
562         ContentiousClaimable {
563                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
564                 /// required to do so.
565                 claimable_amount_satoshis: u64,
566                 /// The height at which the counterparty may be able to claim the balance if we have not
567                 /// done so.
568                 timeout_height: u32,
569         },
570         /// HTLCs which we sent to our counterparty which are claimable after a timeout (less on-chain
571         /// fees) if the counterparty does not know the preimage for the HTLCs. These are somewhat
572         /// likely to be claimed by our counterparty before we do.
573         MaybeClaimableHTLCAwaitingTimeout {
574                 /// The amount available to claim, in satoshis, excluding the on-chain fees which will be
575                 /// required to do so.
576                 claimable_amount_satoshis: u64,
577                 /// The height at which we will be able to claim the balance if our counterparty has not
578                 /// done so.
579                 claimable_height: u32,
580         },
581 }
582 use lightning::chain::channelmonitor::Balance as nativeBalance;
583 impl Balance {
584         #[allow(unused)]
585         pub(crate) fn to_native(&self) -> nativeBalance {
586                 match self {
587                         Balance::ClaimableOnChannelClose {ref claimable_amount_satoshis, } => {
588                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
589                                 nativeBalance::ClaimableOnChannelClose {
590                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
591                                 }
592                         },
593                         Balance::ClaimableAwaitingConfirmations {ref claimable_amount_satoshis, ref confirmation_height, } => {
594                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
595                                 let mut confirmation_height_nonref = (*confirmation_height).clone();
596                                 nativeBalance::ClaimableAwaitingConfirmations {
597                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
598                                         confirmation_height: confirmation_height_nonref,
599                                 }
600                         },
601                         Balance::ContentiousClaimable {ref claimable_amount_satoshis, ref timeout_height, } => {
602                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
603                                 let mut timeout_height_nonref = (*timeout_height).clone();
604                                 nativeBalance::ContentiousClaimable {
605                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
606                                         timeout_height: timeout_height_nonref,
607                                 }
608                         },
609                         Balance::MaybeClaimableHTLCAwaitingTimeout {ref claimable_amount_satoshis, ref claimable_height, } => {
610                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
611                                 let mut claimable_height_nonref = (*claimable_height).clone();
612                                 nativeBalance::MaybeClaimableHTLCAwaitingTimeout {
613                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
614                                         claimable_height: claimable_height_nonref,
615                                 }
616                         },
617                 }
618         }
619         #[allow(unused)]
620         pub(crate) fn into_native(self) -> nativeBalance {
621                 match self {
622                         Balance::ClaimableOnChannelClose {mut claimable_amount_satoshis, } => {
623                                 nativeBalance::ClaimableOnChannelClose {
624                                         claimable_amount_satoshis: claimable_amount_satoshis,
625                                 }
626                         },
627                         Balance::ClaimableAwaitingConfirmations {mut claimable_amount_satoshis, mut confirmation_height, } => {
628                                 nativeBalance::ClaimableAwaitingConfirmations {
629                                         claimable_amount_satoshis: claimable_amount_satoshis,
630                                         confirmation_height: confirmation_height,
631                                 }
632                         },
633                         Balance::ContentiousClaimable {mut claimable_amount_satoshis, mut timeout_height, } => {
634                                 nativeBalance::ContentiousClaimable {
635                                         claimable_amount_satoshis: claimable_amount_satoshis,
636                                         timeout_height: timeout_height,
637                                 }
638                         },
639                         Balance::MaybeClaimableHTLCAwaitingTimeout {mut claimable_amount_satoshis, mut claimable_height, } => {
640                                 nativeBalance::MaybeClaimableHTLCAwaitingTimeout {
641                                         claimable_amount_satoshis: claimable_amount_satoshis,
642                                         claimable_height: claimable_height,
643                                 }
644                         },
645                 }
646         }
647         #[allow(unused)]
648         pub(crate) fn from_native(native: &nativeBalance) -> Self {
649                 match native {
650                         nativeBalance::ClaimableOnChannelClose {ref claimable_amount_satoshis, } => {
651                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
652                                 Balance::ClaimableOnChannelClose {
653                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
654                                 }
655                         },
656                         nativeBalance::ClaimableAwaitingConfirmations {ref claimable_amount_satoshis, ref confirmation_height, } => {
657                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
658                                 let mut confirmation_height_nonref = (*confirmation_height).clone();
659                                 Balance::ClaimableAwaitingConfirmations {
660                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
661                                         confirmation_height: confirmation_height_nonref,
662                                 }
663                         },
664                         nativeBalance::ContentiousClaimable {ref claimable_amount_satoshis, ref timeout_height, } => {
665                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
666                                 let mut timeout_height_nonref = (*timeout_height).clone();
667                                 Balance::ContentiousClaimable {
668                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
669                                         timeout_height: timeout_height_nonref,
670                                 }
671                         },
672                         nativeBalance::MaybeClaimableHTLCAwaitingTimeout {ref claimable_amount_satoshis, ref claimable_height, } => {
673                                 let mut claimable_amount_satoshis_nonref = (*claimable_amount_satoshis).clone();
674                                 let mut claimable_height_nonref = (*claimable_height).clone();
675                                 Balance::MaybeClaimableHTLCAwaitingTimeout {
676                                         claimable_amount_satoshis: claimable_amount_satoshis_nonref,
677                                         claimable_height: claimable_height_nonref,
678                                 }
679                         },
680                 }
681         }
682         #[allow(unused)]
683         pub(crate) fn native_into(native: nativeBalance) -> Self {
684                 match native {
685                         nativeBalance::ClaimableOnChannelClose {mut claimable_amount_satoshis, } => {
686                                 Balance::ClaimableOnChannelClose {
687                                         claimable_amount_satoshis: claimable_amount_satoshis,
688                                 }
689                         },
690                         nativeBalance::ClaimableAwaitingConfirmations {mut claimable_amount_satoshis, mut confirmation_height, } => {
691                                 Balance::ClaimableAwaitingConfirmations {
692                                         claimable_amount_satoshis: claimable_amount_satoshis,
693                                         confirmation_height: confirmation_height,
694                                 }
695                         },
696                         nativeBalance::ContentiousClaimable {mut claimable_amount_satoshis, mut timeout_height, } => {
697                                 Balance::ContentiousClaimable {
698                                         claimable_amount_satoshis: claimable_amount_satoshis,
699                                         timeout_height: timeout_height,
700                                 }
701                         },
702                         nativeBalance::MaybeClaimableHTLCAwaitingTimeout {mut claimable_amount_satoshis, mut claimable_height, } => {
703                                 Balance::MaybeClaimableHTLCAwaitingTimeout {
704                                         claimable_amount_satoshis: claimable_amount_satoshis,
705                                         claimable_height: claimable_height,
706                                 }
707                         },
708                 }
709         }
710 }
711 /// Frees any resources used by the Balance
712 #[no_mangle]
713 pub extern "C" fn Balance_free(this_ptr: Balance) { }
714 /// Creates a copy of the Balance
715 #[no_mangle]
716 pub extern "C" fn Balance_clone(orig: &Balance) -> Balance {
717         orig.clone()
718 }
719 #[no_mangle]
720 /// Utility method to constructs a new ClaimableOnChannelClose-variant Balance
721 pub extern "C" fn Balance_claimable_on_channel_close(claimable_amount_satoshis: u64) -> Balance {
722         Balance::ClaimableOnChannelClose {
723                 claimable_amount_satoshis,
724         }
725 }
726 #[no_mangle]
727 /// Utility method to constructs a new ClaimableAwaitingConfirmations-variant Balance
728 pub extern "C" fn Balance_claimable_awaiting_confirmations(claimable_amount_satoshis: u64, confirmation_height: u32) -> Balance {
729         Balance::ClaimableAwaitingConfirmations {
730                 claimable_amount_satoshis,
731                 confirmation_height,
732         }
733 }
734 #[no_mangle]
735 /// Utility method to constructs a new ContentiousClaimable-variant Balance
736 pub extern "C" fn Balance_contentious_claimable(claimable_amount_satoshis: u64, timeout_height: u32) -> Balance {
737         Balance::ContentiousClaimable {
738                 claimable_amount_satoshis,
739                 timeout_height,
740         }
741 }
742 #[no_mangle]
743 /// Utility method to constructs a new MaybeClaimableHTLCAwaitingTimeout-variant Balance
744 pub extern "C" fn Balance_maybe_claimable_htlcawaiting_timeout(claimable_amount_satoshis: u64, claimable_height: u32) -> Balance {
745         Balance::MaybeClaimableHTLCAwaitingTimeout {
746                 claimable_amount_satoshis,
747                 claimable_height,
748         }
749 }
750 /// Checks if two Balances contain equal inner contents.
751 /// This ignores pointers and is_owned flags and looks at the values in fields.
752 #[no_mangle]
753 pub extern "C" fn Balance_eq(a: &Balance, b: &Balance) -> bool {
754         if &a.to_native() == &b.to_native() { true } else { false }
755 }
756
757 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
758 type nativeChannelMonitor = nativeChannelMonitorImport<crate::lightning::chain::keysinterface::Sign>;
759
760 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
761 /// on-chain transactions to ensure no loss of funds occurs.
762 ///
763 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
764 /// information and are actively monitoring the chain.
765 ///
766 /// Pending Events or updated HTLCs which have not yet been read out by
767 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
768 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
769 /// gotten are fully handled before re-serializing the new state.
770 ///
771 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
772 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
773 /// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
774 /// returned block hash and the the current chain and then reconnecting blocks to get to the
775 /// best chain) upon deserializing the object!
776 #[must_use]
777 #[repr(C)]
778 pub struct ChannelMonitor {
779         /// A pointer to the opaque Rust object.
780
781         /// Nearly everywhere, inner must be non-null, however in places where
782         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
783         pub inner: *mut nativeChannelMonitor,
784         /// Indicates that this is the only struct which contains the same pointer.
785
786         /// Rust functions which take ownership of an object provided via an argument require
787         /// this to be true and invalidate the object pointed to by inner.
788         pub is_owned: bool,
789 }
790
791 impl Drop for ChannelMonitor {
792         fn drop(&mut self) {
793                 if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
794                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
795                 }
796         }
797 }
798 /// Frees any resources used by the ChannelMonitor, if is_owned is set and inner is non-NULL.
799 #[no_mangle]
800 pub extern "C" fn ChannelMonitor_free(this_obj: ChannelMonitor) { }
801 #[allow(unused)]
802 /// Used only if an object of this type is returned as a trait impl by a method
803 extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
804         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); }
805 }
806 #[allow(unused)]
807 impl ChannelMonitor {
808         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelMonitor {
809                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
810         }
811         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelMonitor {
812                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
813         }
814         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
815         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
816                 assert!(self.is_owned);
817                 let ret = ObjOps::untweak_ptr(self.inner);
818                 self.inner = std::ptr::null_mut();
819                 ret
820         }
821 }
822 #[no_mangle]
823 /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read
824 pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
825         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
826 }
827 #[no_mangle]
828 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
829         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
830 }
831 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
832 /// itself.
833 ///
834 /// panics if the given update is not the next update by update_id.
835 #[must_use]
836 #[no_mangle]
837 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ {
838         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_monitor(updates.get_native_ref(), broadcaster, fee_estimator, logger);
839         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::MonitorUpdateError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
840         local_ret
841 }
842
843 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
844 /// ChannelMonitor.
845 #[must_use]
846 #[no_mangle]
847 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 {
848         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_update_id();
849         ret
850 }
851
852 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
853 #[must_use]
854 #[no_mangle]
855 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ {
856         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_funding_txo();
857         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();
858         local_ret
859 }
860
861 /// Gets a list of txids, with their output scripts (in the order they appear in the
862 /// transaction), which we must learn about spends of via block_connected().
863 #[must_use]
864 #[no_mangle]
865 pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ {
866         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_outputs_to_watch();
867         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 }); };
868         local_ret.into()
869 }
870
871 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
872 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
873 /// have been registered.
874 #[no_mangle]
875 pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor, filter: &crate::lightning::chain::Filter) {
876         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.load_outputs_to_watch(filter)
877 }
878
879 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
880 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
881 #[must_use]
882 #[no_mangle]
883 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
884         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_monitor_events();
885         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
886         local_ret.into()
887 }
888
889 /// Gets the list of pending events which were generated by previous actions, clearing the list
890 /// in the process.
891 ///
892 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
893 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
894 /// no internal locking in ChannelMonitors.
895 #[must_use]
896 #[no_mangle]
897 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
898         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_pending_events();
899         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::Event::native_into(item) }); };
900         local_ret.into()
901 }
902
903 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
904 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
905 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
906 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
907 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
908 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
909 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
910 /// out-of-band the other node operator to coordinate with him if option is available to you.
911 /// In any-case, choice is up to the user.
912 #[must_use]
913 #[no_mangle]
914 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &ChannelMonitor, logger: &crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
915         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_latest_holder_commitment_txn(logger);
916         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::Transaction::from_bitcoin(&item) }); };
917         local_ret.into()
918 }
919
920 /// Processes transactions in a newly connected block, which may result in any of the following:
921 /// - update the monitor's state against resolved HTLCs
922 /// - punish the counterparty in the case of seeing a revoked commitment transaction
923 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
924 /// - detect settled outputs for later spending
925 /// - schedule and bump any in-flight claims
926 ///
927 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
928 /// [`get_outputs_to_watch`].
929 ///
930 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
931 #[must_use]
932 #[no_mangle]
933 pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
934         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 }); };
935         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);
936         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 }); };
937         local_ret.into()
938 }
939
940 /// Determines if the disconnected block contained any transactions of interest and updates
941 /// appropriately.
942 #[no_mangle]
943 pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) {
944         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
945 }
946
947 /// Processes transactions confirmed in a block with the given header and height, returning new
948 /// outputs to watch. See [`block_connected`] for details.
949 ///
950 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
951 /// blocks. See [`chain::Confirm`] for calling expectations.
952 ///
953 /// [`block_connected`]: Self::block_connected
954 #[must_use]
955 #[no_mangle]
956 pub extern "C" fn ChannelMonitor_transactions_confirmed(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
957         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 }); };
958         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);
959         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 }); };
960         local_ret.into()
961 }
962
963 /// Processes a transaction that was reorganized out of the chain.
964 ///
965 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
966 /// than blocks. See [`chain::Confirm`] for calling expectations.
967 ///
968 /// [`block_disconnected`]: Self::block_disconnected
969 #[no_mangle]
970 pub extern "C" fn ChannelMonitor_transaction_unconfirmed(this_arg: &ChannelMonitor, txid: *const [u8; 32], mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) {
971         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger)
972 }
973
974 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
975 /// [`block_connected`] for details.
976 ///
977 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
978 /// blocks. See [`chain::Confirm`] for calling expectations.
979 ///
980 /// [`block_connected`]: Self::block_connected
981 #[must_use]
982 #[no_mangle]
983 pub extern "C" fn ChannelMonitor_best_block_updated(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut logger: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionOutputsZ {
984         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);
985         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 }); };
986         local_ret.into()
987 }
988
989 /// Returns the set of txids that should be monitored for re-organization out of the chain.
990 #[must_use]
991 #[no_mangle]
992 pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_TxidZ {
993         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_relevant_txids();
994         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
995         local_ret.into()
996 }
997
998 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
999 /// [`chain::Confirm`] interfaces.
1000 #[must_use]
1001 #[no_mangle]
1002 pub extern "C" fn ChannelMonitor_current_best_block(this_arg: &ChannelMonitor) -> crate::lightning::chain::BestBlock {
1003         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
1004         crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
1005 }
1006
1007 /// Gets the balances in this channel which are either claimable by us if we were to
1008 /// force-close the channel now or which are claimable on-chain (possibly awaiting
1009 /// confirmation).
1010 ///
1011 /// Any balances in the channel which are available on-chain (excluding on-chain fees) are
1012 /// included here until an [`Event::SpendableOutputs`] event has been generated for the
1013 /// balance, or until our counterparty has claimed the balance and accrued several
1014 /// confirmations on the claim transaction.
1015 ///
1016 /// Note that the balances available when you or your counterparty have broadcasted revoked
1017 /// state(s) may not be fully captured here.
1018 ///
1019 /// See [`Balance`] for additional details on the types of claimable balances which
1020 /// may be returned here and their meanings.
1021 #[must_use]
1022 #[no_mangle]
1023 pub extern "C" fn ChannelMonitor_get_claimable_balances(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_BalanceZ {
1024         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_claimable_balances();
1025         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::Balance::native_into(item) }); };
1026         local_ret.into()
1027 }
1028
1029 /// `Persist` defines behavior for persisting channel monitors: this could mean
1030 /// writing once to disk, and/or uploading to one or more backup services.
1031 ///
1032 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
1033 /// to disk/backups. And, on every update, you **must** persist either the
1034 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
1035 /// of situations such as revoking a transaction, then crashing before this
1036 /// revocation can be persisted, then unintentionally broadcasting a revoked
1037 /// transaction and losing money. This is a risk because previous channel states
1038 /// are toxic, so it's important that whatever channel state is persisted is
1039 /// kept up-to-date.
1040 #[repr(C)]
1041 pub struct Persist {
1042         /// An opaque pointer which is passed to your function implementations as an argument.
1043         /// This has no meaning in the LDK, and can be NULL or any other value.
1044         pub this_arg: *mut c_void,
1045         /// Persist a new channel's data. The data can be stored any way you want, but
1046         /// the identifier provided by Rust-Lightning is the channel's outpoint (and
1047         /// it is up to you to maintain a correct mapping between the outpoint and the
1048         /// stored channel data). Note that you **must** persist every new monitor to
1049         /// disk. See the `Persist` trait documentation for more details.
1050         ///
1051         /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
1052         /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
1053         #[must_use]
1054         pub persist_new_channel: extern "C" fn (this_arg: *const c_void, id: crate::lightning::chain::transaction::OutPoint, data: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
1055         /// Update one channel's data. The provided `ChannelMonitor` has already
1056         /// applied the given update.
1057         ///
1058         /// Note that on every update, you **must** persist either the
1059         /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
1060         /// the `Persist` trait documentation for more details.
1061         ///
1062         /// If an implementer chooses to persist the updates only, they need to make
1063         /// sure that all the updates are applied to the `ChannelMonitors` *before*
1064         /// the set of channel monitors is given to the `ChannelManager`
1065         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
1066         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
1067         /// persisted, then there is no need to persist individual updates.
1068         ///
1069         /// Note that there could be a performance tradeoff between persisting complete
1070         /// channel monitors on every update vs. persisting only updates and applying
1071         /// them in batches. The size of each monitor grows `O(number of state updates)`
1072         /// whereas updates are small and `O(1)`.
1073         ///
1074         /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
1075         /// [`ChannelMonitorUpdate::write`] for writing out an update, and
1076         /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
1077         #[must_use]
1078         pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, id: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
1079         /// Frees any resources associated with this object given its this_arg pointer.
1080         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
1081         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
1082 }
1083 unsafe impl Send for Persist {}
1084 unsafe impl Sync for Persist {}
1085 #[no_mangle]
1086 pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist {
1087         Persist {
1088                 this_arg: orig.this_arg,
1089                 persist_new_channel: Clone::clone(&orig.persist_new_channel),
1090                 update_persisted_channel: Clone::clone(&orig.update_persisted_channel),
1091                 free: Clone::clone(&orig.free),
1092         }
1093 }
1094
1095 use lightning::chain::channelmonitor::Persist as rustPersist;
1096 impl rustPersist<crate::lightning::chain::keysinterface::Sign> for Persist {
1097         fn persist_new_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
1098                 let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false });
1099                 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() })};
1100                 local_ret
1101         }
1102         fn update_persisted_channel(&self, mut id: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
1103                 let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const _) as *mut _) }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const _) as *mut _) }, is_owned: false });
1104                 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() })};
1105                 local_ret
1106         }
1107 }
1108
1109 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
1110 // directly as a Deref trait in higher-level structs:
1111 impl std::ops::Deref for Persist {
1112         type Target = Self;
1113         fn deref(&self) -> &Self {
1114                 self
1115         }
1116 }
1117 /// Calls the free function if one is set
1118 #[no_mangle]
1119 pub extern "C" fn Persist_free(this_ptr: Persist) { }
1120 impl Drop for Persist {
1121         fn drop(&mut self) {
1122                 if let Some(f) = self.free {
1123                         f(self.this_arg);
1124                 }
1125         }
1126 }
1127 #[no_mangle]
1128 /// Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write
1129 pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
1130         let arg_conv = arg;
1131         let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1132         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
1133         local_res
1134 }