Merge pull request #39 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 bitcoin::hashes::Hash;
25 use crate::c_types::*;
26
27
28 use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport;
29 type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport;
30
31 /// An update generated by the underlying Channel itself which contains some new information the
32 /// ChannelMonitor should be made aware of.
33 #[must_use]
34 #[repr(C)]
35 pub struct ChannelMonitorUpdate {
36         /// A pointer to the opaque Rust object.
37
38         /// Nearly everywhere, inner must be non-null, however in places where
39         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
40         pub inner: *mut nativeChannelMonitorUpdate,
41         /// Indicates that this is the only struct which contains the same pointer.
42
43         /// Rust functions which take ownership of an object provided via an argument require
44         /// this to be true and invalidate the object pointed to by inner.
45         pub is_owned: bool,
46 }
47
48 impl Drop for ChannelMonitorUpdate {
49         fn drop(&mut self) {
50                 if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
51                         let _ = unsafe { Box::from_raw(self.inner) };
52                 }
53         }
54 }
55 /// Frees any resources used by the ChannelMonitorUpdate, if is_owned is set and inner is non-NULL.
56 #[no_mangle]
57 pub extern "C" fn ChannelMonitorUpdate_free(this_obj: ChannelMonitorUpdate) { }
58 #[allow(unused)]
59 /// Used only if an object of this type is returned as a trait impl by a method
60 extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
61         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); }
62 }
63 #[allow(unused)]
64 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
65 impl ChannelMonitorUpdate {
66         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
67                 assert!(self.is_owned);
68                 let ret = self.inner;
69                 self.inner = std::ptr::null_mut();
70                 ret
71         }
72 }
73 /// The sequence number of this update. Updates *must* be replayed in-order according to this
74 /// sequence number (and updates may panic if they are not). The update_id values are strictly
75 /// increasing and increase by one for each new update, with one exception specified below.
76 ///
77 /// This sequence number is also used to track up to which points updates which returned
78 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
79 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
80 ///
81 /// The only instance where update_id values are not strictly increasing is the case where we
82 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
83 /// its docs for more details.
84 #[no_mangle]
85 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
86         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_id;
87         *inner_val
88 }
89 /// The sequence number of this update. Updates *must* be replayed in-order according to this
90 /// sequence number (and updates may panic if they are not). The update_id values are strictly
91 /// increasing and increase by one for each new update, with one exception specified below.
92 ///
93 /// This sequence number is also used to track up to which points updates which returned
94 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
95 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
96 ///
97 /// The only instance where update_id values are not strictly increasing is the case where we
98 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
99 /// its docs for more details.
100 #[no_mangle]
101 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
102         unsafe { &mut *this_ptr.inner }.update_id = val;
103 }
104 impl Clone for ChannelMonitorUpdate {
105         fn clone(&self) -> Self {
106                 Self {
107                         inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
108                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
109                         is_owned: true,
110                 }
111         }
112 }
113 #[allow(unused)]
114 /// Used only if an object of this type is returned as a trait impl by a method
115 pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
116         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
117 }
118 #[no_mangle]
119 /// Creates a copy of the ChannelMonitorUpdate
120 pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
121         orig.clone()
122 }
123 /// If:
124 ///    (1) a channel has been force closed and
125 ///    (2) we receive a preimage from a forward link that allows us to spend an HTLC output on
126 ///        this channel's (the backward link's) broadcasted commitment transaction
127 /// then we allow the `ChannelManager` to send a `ChannelMonitorUpdate` with this update ID,
128 /// with the update providing said payment preimage. No other update types are allowed after
129 /// force-close.
130
131 #[no_mangle]
132 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
133 #[no_mangle]
134 /// Serialize the ChannelMonitorUpdate object into a byte array which can be read by ChannelMonitorUpdate_read
135 pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
136         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
137 }
138 #[no_mangle]
139 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
140         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
141 }
142 #[no_mangle]
143 /// Read a ChannelMonitorUpdate from a byte array, created by ChannelMonitorUpdate_write
144 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
145         let res = crate::c_types::deserialize_obj(ser);
146         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
147         local_res
148 }
149 /// An error enum representing a failure to persist a channel monitor update.
150 #[must_use]
151 #[derive(Clone)]
152 #[repr(C)]
153 pub enum ChannelMonitorUpdateErr {
154         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
155         /// our state failed, but is expected to succeed at some point in the future).
156         ///
157         /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
158         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
159         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
160         /// restore the channel to an operational state.
161         ///
162         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
163         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
164         /// writing out the latest ChannelManager state.
165         ///
166         /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
167         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
168         /// to claim it on this channel) and those updates must be applied wherever they can be. At
169         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
170         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
171         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
172         /// been \"frozen\".
173         ///
174         /// Note that even if updates made after TemporaryFailure succeed you must still call
175         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
176         /// operation.
177         ///
178         /// Note that the update being processed here will not be replayed for you when you call
179         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
180         /// with the persisted ChannelMonitor on your own local disk prior to returning a
181         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
182         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
183         /// reload-time.
184         ///
185         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
186         /// remote location (with local copies persisted immediately), it is anticipated that all
187         /// updates will return TemporaryFailure until the remote copies could be updated.
188         TemporaryFailure,
189         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
190         /// different watchtower and cannot update with all watchtowers that were previously informed
191         /// of this channel).
192         ///
193         /// At reception of this error, ChannelManager will force-close the channel and return at
194         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
195         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
196         /// update must be rejected.
197         ///
198         /// This failure may also signal a failure to update the local persisted copy of one of
199         /// the channel monitor instance.
200         ///
201         /// Note that even when you fail a holder commitment transaction update, you must store the
202         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
203         /// broadcasts it (e.g distributed channel-monitor deployment)
204         ///
205         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
206         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
207         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
208         /// lagging behind on block processing.
209         PermanentFailure,
210 }
211 use lightning::chain::channelmonitor::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
212 impl ChannelMonitorUpdateErr {
213         #[allow(unused)]
214         pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
215                 match self {
216                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
217                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
218                 }
219         }
220         #[allow(unused)]
221         pub(crate) fn into_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 from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
229                 match native {
230                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
231                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
232                 }
233         }
234         #[allow(unused)]
235         pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
236                 match native {
237                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
238                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
239                 }
240         }
241 }
242 /// Creates a copy of the ChannelMonitorUpdateErr
243 #[no_mangle]
244 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
245         orig.clone()
246 }
247 #[no_mangle]
248 /// Utility method to constructs a new TemporaryFailure-variant ChannelMonitorUpdateErr
249 pub extern "C" fn ChannelMonitorUpdateErr_temporary_failure() -> ChannelMonitorUpdateErr {
250         ChannelMonitorUpdateErr::TemporaryFailure}
251 #[no_mangle]
252 /// Utility method to constructs a new PermanentFailure-variant ChannelMonitorUpdateErr
253 pub extern "C" fn ChannelMonitorUpdateErr_permanent_failure() -> ChannelMonitorUpdateErr {
254         ChannelMonitorUpdateErr::PermanentFailure}
255
256 use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport;
257 type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport;
258
259 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
260 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
261 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
262 /// corrupted.
263 /// Contains a developer-readable error message.
264 #[must_use]
265 #[repr(C)]
266 pub struct MonitorUpdateError {
267         /// A pointer to the opaque Rust object.
268
269         /// Nearly everywhere, inner must be non-null, however in places where
270         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
271         pub inner: *mut nativeMonitorUpdateError,
272         /// Indicates that this is the only struct which contains the same pointer.
273
274         /// Rust functions which take ownership of an object provided via an argument require
275         /// this to be true and invalidate the object pointed to by inner.
276         pub is_owned: bool,
277 }
278
279 impl Drop for MonitorUpdateError {
280         fn drop(&mut self) {
281                 if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) {
282                         let _ = unsafe { Box::from_raw(self.inner) };
283                 }
284         }
285 }
286 /// Frees any resources used by the MonitorUpdateError, if is_owned is set and inner is non-NULL.
287 #[no_mangle]
288 pub extern "C" fn MonitorUpdateError_free(this_obj: MonitorUpdateError) { }
289 #[allow(unused)]
290 /// Used only if an object of this type is returned as a trait impl by a method
291 extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
292         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); }
293 }
294 #[allow(unused)]
295 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
296 impl MonitorUpdateError {
297         pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
298                 assert!(self.is_owned);
299                 let ret = self.inner;
300                 self.inner = std::ptr::null_mut();
301                 ret
302         }
303 }
304 impl Clone for MonitorUpdateError {
305         fn clone(&self) -> Self {
306                 Self {
307                         inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else {
308                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
309                         is_owned: true,
310                 }
311         }
312 }
313 #[allow(unused)]
314 /// Used only if an object of this type is returned as a trait impl by a method
315 pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void {
316         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void
317 }
318 #[no_mangle]
319 /// Creates a copy of the MonitorUpdateError
320 pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError {
321         orig.clone()
322 }
323 /// An event to be processed by the ChannelManager.
324 #[must_use]
325 #[derive(Clone)]
326 #[repr(C)]
327 pub enum MonitorEvent {
328         /// A monitor event containing an HTLCUpdate.
329         HTLCEvent(crate::lightning::chain::channelmonitor::HTLCUpdate),
330         /// A monitor event that the Channel's commitment transaction was broadcasted.
331         CommitmentTxBroadcasted(crate::lightning::chain::transaction::OutPoint),
332 }
333 use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent;
334 impl MonitorEvent {
335         #[allow(unused)]
336         pub(crate) fn to_native(&self) -> nativeMonitorEvent {
337                 match self {
338                         MonitorEvent::HTLCEvent (ref a, ) => {
339                                 let mut a_nonref = (*a).clone();
340                                 nativeMonitorEvent::HTLCEvent (
341                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
342                                 )
343                         },
344                         MonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
345                                 let mut a_nonref = (*a).clone();
346                                 nativeMonitorEvent::CommitmentTxBroadcasted (
347                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
348                                 )
349                         },
350                 }
351         }
352         #[allow(unused)]
353         pub(crate) fn into_native(self) -> nativeMonitorEvent {
354                 match self {
355                         MonitorEvent::HTLCEvent (mut a, ) => {
356                                 nativeMonitorEvent::HTLCEvent (
357                                         *unsafe { Box::from_raw(a.take_inner()) },
358                                 )
359                         },
360                         MonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
361                                 nativeMonitorEvent::CommitmentTxBroadcasted (
362                                         *unsafe { Box::from_raw(a.take_inner()) },
363                                 )
364                         },
365                 }
366         }
367         #[allow(unused)]
368         pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
369                 match native {
370                         nativeMonitorEvent::HTLCEvent (ref a, ) => {
371                                 let mut a_nonref = (*a).clone();
372                                 MonitorEvent::HTLCEvent (
373                                         crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
374                                 )
375                         },
376                         nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
377                                 let mut a_nonref = (*a).clone();
378                                 MonitorEvent::CommitmentTxBroadcasted (
379                                         crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
380                                 )
381                         },
382                 }
383         }
384         #[allow(unused)]
385         pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
386                 match native {
387                         nativeMonitorEvent::HTLCEvent (mut a, ) => {
388                                 MonitorEvent::HTLCEvent (
389                                         crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true },
390                                 )
391                         },
392                         nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
393                                 MonitorEvent::CommitmentTxBroadcasted (
394                                         crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true },
395                                 )
396                         },
397                 }
398         }
399 }
400 /// Frees any resources used by the MonitorEvent
401 #[no_mangle]
402 pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
403 /// Creates a copy of the MonitorEvent
404 #[no_mangle]
405 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
406         orig.clone()
407 }
408 #[no_mangle]
409 /// Utility method to constructs a new HTLCEvent-variant MonitorEvent
410 pub extern "C" fn MonitorEvent_htlcevent(a: crate::lightning::chain::channelmonitor::HTLCUpdate) -> MonitorEvent {
411         MonitorEvent::HTLCEvent(a, )
412 }
413 #[no_mangle]
414 /// Utility method to constructs a new CommitmentTxBroadcasted-variant MonitorEvent
415 pub extern "C" fn MonitorEvent_commitment_tx_broadcasted(a: crate::lightning::chain::transaction::OutPoint) -> MonitorEvent {
416         MonitorEvent::CommitmentTxBroadcasted(a, )
417 }
418
419 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
420 type nativeHTLCUpdate = nativeHTLCUpdateImport;
421
422 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
423 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
424 /// preimage claim backward will lead to loss of funds.
425 #[must_use]
426 #[repr(C)]
427 pub struct HTLCUpdate {
428         /// A pointer to the opaque Rust object.
429
430         /// Nearly everywhere, inner must be non-null, however in places where
431         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
432         pub inner: *mut nativeHTLCUpdate,
433         /// Indicates that this is the only struct which contains the same pointer.
434
435         /// Rust functions which take ownership of an object provided via an argument require
436         /// this to be true and invalidate the object pointed to by inner.
437         pub is_owned: bool,
438 }
439
440 impl Drop for HTLCUpdate {
441         fn drop(&mut self) {
442                 if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
443                         let _ = unsafe { Box::from_raw(self.inner) };
444                 }
445         }
446 }
447 /// Frees any resources used by the HTLCUpdate, if is_owned is set and inner is non-NULL.
448 #[no_mangle]
449 pub extern "C" fn HTLCUpdate_free(this_obj: HTLCUpdate) { }
450 #[allow(unused)]
451 /// Used only if an object of this type is returned as a trait impl by a method
452 extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
453         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); }
454 }
455 #[allow(unused)]
456 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
457 impl HTLCUpdate {
458         pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
459                 assert!(self.is_owned);
460                 let ret = self.inner;
461                 self.inner = std::ptr::null_mut();
462                 ret
463         }
464 }
465 impl Clone for HTLCUpdate {
466         fn clone(&self) -> Self {
467                 Self {
468                         inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
469                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
470                         is_owned: true,
471                 }
472         }
473 }
474 #[allow(unused)]
475 /// Used only if an object of this type is returned as a trait impl by a method
476 pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
477         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCUpdate)).clone() })) as *mut c_void
478 }
479 #[no_mangle]
480 /// Creates a copy of the HTLCUpdate
481 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
482         orig.clone()
483 }
484 #[no_mangle]
485 /// Serialize the HTLCUpdate object into a byte array which can be read by HTLCUpdate_read
486 pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
487         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
488 }
489 #[no_mangle]
490 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
491         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
492 }
493 #[no_mangle]
494 /// Read a HTLCUpdate from a byte array, created by HTLCUpdate_write
495 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
496         let res = crate::c_types::deserialize_obj(ser);
497         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
498         local_res
499 }
500 /// Number of blocks we wait on seeing a HTLC output being solved before we fail corresponding inbound
501 /// HTLCs. This prevents us from failing backwards and then getting a reorg resulting in us losing money.
502
503 #[no_mangle]
504 pub static ANTI_REORG_DELAY: u32 = lightning::chain::channelmonitor::ANTI_REORG_DELAY;
505
506 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
507 type nativeChannelMonitor = nativeChannelMonitorImport<crate::lightning::chain::keysinterface::Sign>;
508
509 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
510 /// on-chain transactions to ensure no loss of funds occurs.
511 ///
512 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
513 /// information and are actively monitoring the chain.
514 ///
515 /// Pending Events or updated HTLCs which have not yet been read out by
516 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
517 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
518 /// gotten are fully handled before re-serializing the new state.
519 ///
520 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
521 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
522 /// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
523 /// returned block hash and the the current chain and then reconnecting blocks to get to the
524 /// best chain) upon deserializing the object!
525 #[must_use]
526 #[repr(C)]
527 pub struct ChannelMonitor {
528         /// A pointer to the opaque Rust object.
529
530         /// Nearly everywhere, inner must be non-null, however in places where
531         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
532         pub inner: *mut nativeChannelMonitor,
533         /// Indicates that this is the only struct which contains the same pointer.
534
535         /// Rust functions which take ownership of an object provided via an argument require
536         /// this to be true and invalidate the object pointed to by inner.
537         pub is_owned: bool,
538 }
539
540 impl Drop for ChannelMonitor {
541         fn drop(&mut self) {
542                 if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
543                         let _ = unsafe { Box::from_raw(self.inner) };
544                 }
545         }
546 }
547 /// Frees any resources used by the ChannelMonitor, if is_owned is set and inner is non-NULL.
548 #[no_mangle]
549 pub extern "C" fn ChannelMonitor_free(this_obj: ChannelMonitor) { }
550 #[allow(unused)]
551 /// Used only if an object of this type is returned as a trait impl by a method
552 extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
553         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); }
554 }
555 #[allow(unused)]
556 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
557 impl ChannelMonitor {
558         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
559                 assert!(self.is_owned);
560                 let ret = self.inner;
561                 self.inner = std::ptr::null_mut();
562                 ret
563         }
564 }
565 #[no_mangle]
566 /// Serialize the ChannelMonitor object into a byte array which can be read by ChannelMonitor_read
567 pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
568         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
569 }
570 #[no_mangle]
571 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
572         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
573 }
574 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
575 /// itself.
576 ///
577 /// panics if the given update is not the next update by update_id.
578 #[must_use]
579 #[no_mangle]
580 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 {
581         let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger);
582         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
583         local_ret
584 }
585
586 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
587 /// ChannelMonitor.
588 #[must_use]
589 #[no_mangle]
590 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 {
591         let mut ret = unsafe { &*this_arg.inner }.get_latest_update_id();
592         ret
593 }
594
595 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
596 #[must_use]
597 #[no_mangle]
598 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ {
599         let mut ret = unsafe { &*this_arg.inner }.get_funding_txo();
600         let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, orig_ret_1.into_bytes().into()).into();
601         local_ret
602 }
603
604 /// Gets a list of txids, with their output scripts (in the order they appear in the
605 /// transaction), which we must learn about spends of via block_connected().
606 #[must_use]
607 #[no_mangle]
608 pub extern "C" fn ChannelMonitor_get_outputs_to_watch(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32ScriptZZZZ {
609         let mut ret = unsafe { &*this_arg.inner }.get_outputs_to_watch();
610         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 }); };
611         local_ret.into()
612 }
613
614 /// Loads the funding txo and outputs to watch into the given `chain::Filter` by repeatedly
615 /// calling `chain::Filter::register_output` and `chain::Filter::register_tx` until all outputs
616 /// have been registered.
617 #[no_mangle]
618 pub extern "C" fn ChannelMonitor_load_outputs_to_watch(this_arg: &ChannelMonitor, filter: &crate::lightning::chain::Filter) {
619         unsafe { &*this_arg.inner }.load_outputs_to_watch(filter)
620 }
621
622 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
623 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
624 #[must_use]
625 #[no_mangle]
626 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
627         let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_monitor_events();
628         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
629         local_ret.into()
630 }
631
632 /// Gets the list of pending events which were generated by previous actions, clearing the list
633 /// in the process.
634 ///
635 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
636 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
637 /// no internal locking in ChannelMonitors.
638 #[must_use]
639 #[no_mangle]
640 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
641         let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_events();
642         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::Event::native_into(item) }); };
643         local_ret.into()
644 }
645
646 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
647 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
648 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
649 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
650 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
651 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
652 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
653 /// out-of-band the other node operator to coordinate with him if option is available to you.
654 /// In any-case, choice is up to the user.
655 #[must_use]
656 #[no_mangle]
657 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 {
658         let mut ret = unsafe { &*this_arg.inner }.get_latest_holder_commitment_txn(logger);
659         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::Transaction::from_bitcoin(&item) }); };
660         local_ret.into()
661 }
662
663 /// Processes transactions in a newly connected block, which may result in any of the following:
664 /// - update the monitor's state against resolved HTLCs
665 /// - punish the counterparty in the case of seeing a revoked commitment transaction
666 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
667 /// - detect settled outputs for later spending
668 /// - schedule and bump any in-flight claims
669 ///
670 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
671 /// [`get_outputs_to_watch`].
672 ///
673 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
674 #[must_use]
675 #[no_mangle]
676 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 {
677         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 }); };
678         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);
679         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 }); };
680         local_ret.into()
681 }
682
683 /// Determines if the disconnected block contained any transactions of interest and updates
684 /// appropriately.
685 #[no_mangle]
686 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) {
687         unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
688 }
689
690 /// Processes transactions confirmed in a block with the given header and height, returning new
691 /// outputs to watch. See [`block_connected`] for details.
692 ///
693 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
694 /// blocks. See [`chain::Confirm`] for calling expectations.
695 ///
696 /// [`block_connected`]: Self::block_connected
697 #[must_use]
698 #[no_mangle]
699 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 {
700         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 }); };
701         let mut ret = unsafe { &*this_arg.inner }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height, broadcaster, fee_estimator, logger);
702         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 }); };
703         local_ret.into()
704 }
705
706 /// Processes a transaction that was reorganized out of the chain.
707 ///
708 /// Used instead of [`block_disconnected`] by clients that are notified of transactions rather
709 /// than blocks. See [`chain::Confirm`] for calling expectations.
710 ///
711 /// [`block_disconnected`]: Self::block_disconnected
712 #[no_mangle]
713 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) {
714         unsafe { &*this_arg.inner }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap(), broadcaster, fee_estimator, logger)
715 }
716
717 /// Updates the monitor with the current best chain tip, returning new outputs to watch. See
718 /// [`block_connected`] for details.
719 ///
720 /// Used instead of [`block_connected`] by clients that are notified of transactions rather than
721 /// blocks. See [`chain::Confirm`] for calling expectations.
722 ///
723 /// [`block_connected`]: Self::block_connected
724 #[must_use]
725 #[no_mangle]
726 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 {
727         let mut ret = unsafe { &*this_arg.inner }.best_block_updated(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger);
728         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 }); };
729         local_ret.into()
730 }
731
732 /// Returns the set of txids that should be monitored for re-organization out of the chain.
733 #[must_use]
734 #[no_mangle]
735 pub extern "C" fn ChannelMonitor_get_relevant_txids(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_TxidZ {
736         let mut ret = unsafe { &*this_arg.inner }.get_relevant_txids();
737         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
738         local_ret.into()
739 }
740
741 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
742 /// [`chain::Confirm`] interfaces.
743 #[must_use]
744 #[no_mangle]
745 pub extern "C" fn ChannelMonitor_current_best_block(this_arg: &ChannelMonitor) -> crate::lightning::chain::BestBlock {
746         let mut ret = unsafe { &*this_arg.inner }.current_best_block();
747         crate::lightning::chain::BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
748 }
749
750 /// `Persist` defines behavior for persisting channel monitors: this could mean
751 /// writing once to disk, and/or uploading to one or more backup services.
752 ///
753 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
754 /// to disk/backups. And, on every update, you **must** persist either the
755 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
756 /// of situations such as revoking a transaction, then crashing before this
757 /// revocation can be persisted, then unintentionally broadcasting a revoked
758 /// transaction and losing money. This is a risk because previous channel states
759 /// are toxic, so it's important that whatever channel state is persisted is
760 /// kept up-to-date.
761 #[repr(C)]
762 pub struct Persist {
763         /// An opaque pointer which is passed to your function implementations as an argument.
764         /// This has no meaning in the LDK, and can be NULL or any other value.
765         pub this_arg: *mut c_void,
766         /// Persist a new channel's data. The data can be stored any way you want, but
767         /// the identifier provided by Rust-Lightning is the channel's outpoint (and
768         /// it is up to you to maintain a correct mapping between the outpoint and the
769         /// stored channel data). Note that you **must** persist every new monitor to
770         /// disk. See the `Persist` trait documentation for more details.
771         ///
772         /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
773         /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
774         #[must_use]
775         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,
776         /// Update one channel's data. The provided `ChannelMonitor` has already
777         /// applied the given update.
778         ///
779         /// Note that on every update, you **must** persist either the
780         /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
781         /// the `Persist` trait documentation for more details.
782         ///
783         /// If an implementer chooses to persist the updates only, they need to make
784         /// sure that all the updates are applied to the `ChannelMonitors` *before*
785         /// the set of channel monitors is given to the `ChannelManager`
786         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
787         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
788         /// persisted, then there is no need to persist individual updates.
789         ///
790         /// Note that there could be a performance tradeoff between persisting complete
791         /// channel monitors on every update vs. persisting only updates and applying
792         /// them in batches. The size of each monitor grows `O(number of state updates)`
793         /// whereas updates are small and `O(1)`.
794         ///
795         /// See [`ChannelMonitor::write`] for writing out a `ChannelMonitor`,
796         /// [`ChannelMonitorUpdate::write`] for writing out an update, and
797         /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
798         #[must_use]
799         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,
800         /// Frees any resources associated with this object given its this_arg pointer.
801         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
802         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
803 }
804 unsafe impl Send for Persist {}
805 unsafe impl Sync for Persist {}
806 #[no_mangle]
807 pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist {
808         Persist {
809                 this_arg: orig.this_arg,
810                 persist_new_channel: Clone::clone(&orig.persist_new_channel),
811                 update_persisted_channel: Clone::clone(&orig.update_persisted_channel),
812                 free: Clone::clone(&orig.free),
813         }
814 }
815
816 use lightning::chain::channelmonitor::Persist as rustPersist;
817 impl rustPersist<crate::lightning::chain::keysinterface::Sign> for Persist {
818         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> {
819                 let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
820                 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() })};
821                 local_ret
822         }
823         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> {
824                 let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
825                 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() })};
826                 local_ret
827         }
828 }
829
830 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
831 // directly as a Deref trait in higher-level structs:
832 impl std::ops::Deref for Persist {
833         type Target = Self;
834         fn deref(&self) -> &Self {
835                 self
836         }
837 }
838 /// Calls the free function if one is set
839 #[no_mangle]
840 pub extern "C" fn Persist_free(this_ptr: Persist) { }
841 impl Drop for Persist {
842         fn drop(&mut self) {
843                 if let Some(f) = self.free {
844                         f(self.this_arg);
845                 }
846         }
847 }
848 #[no_mangle]
849 /// Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write
850 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 {
851         let arg_conv = arg;
852         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);
853         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
854         local_res
855 }