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