9fab7e0466a8f19ce06cd01bdd5db91e27847edb
[ldk-c-bindings] / lightning-c-bindings / src / chain / channelmonitor.rs
1 //! The logic to monitor for on-chain transactions and create the relevant claim responses lives
2 //! here.
3 //!
4 //! ChannelMonitor objects are generated by ChannelManager in response to relevant
5 //! messages/actions, and MUST be persisted to disk (and, preferably, remotely) before progress can
6 //! be made in responding to certain messages, see [`chain::Watch`] for more.
7 //!
8 //! Note that ChannelMonitors are an important part of the lightning trust model and a copy of the
9 //! latest ChannelMonitor must always be actively monitoring for chain updates (and no out-of-date
10 //! ChannelMonitors should do so). Thus, if you're building rust-lightning into an HSM or other
11 //! security-domain-separated system design, you should consider having multiple paths for
12 //! ChannelMonitors to get out of the HSM and onto monitoring devices.
13 //!
14 //! [`chain::Watch`]: ../trait.Watch.html
15
16 use std::ffi::c_void;
17 use bitcoin::hashes::Hash;
18 use crate::c_types::*;
19
20
21 use lightning::chain::channelmonitor::ChannelMonitorUpdate as nativeChannelMonitorUpdateImport;
22 type nativeChannelMonitorUpdate = nativeChannelMonitorUpdateImport;
23
24 /// An update generated by the underlying Channel itself which contains some new information the
25 /// ChannelMonitor should be made aware of.
26 #[must_use]
27 #[repr(C)]
28 pub struct ChannelMonitorUpdate {
29         /// Nearly everywhere, inner must be non-null, however in places where
30         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
31         pub inner: *mut nativeChannelMonitorUpdate,
32         pub is_owned: bool,
33 }
34
35 impl Drop for ChannelMonitorUpdate {
36         fn drop(&mut self) {
37                 if self.is_owned && !<*mut nativeChannelMonitorUpdate>::is_null(self.inner) {
38                         let _ = unsafe { Box::from_raw(self.inner) };
39                 }
40         }
41 }
42 #[no_mangle]
43 pub extern "C" fn ChannelMonitorUpdate_free(this_ptr: ChannelMonitorUpdate) { }
44 #[allow(unused)]
45 /// Used only if an object of this type is returned as a trait impl by a method
46 extern "C" fn ChannelMonitorUpdate_free_void(this_ptr: *mut c_void) {
47         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitorUpdate); }
48 }
49 #[allow(unused)]
50 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
51 impl ChannelMonitorUpdate {
52         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitorUpdate {
53                 assert!(self.is_owned);
54                 let ret = self.inner;
55                 self.inner = std::ptr::null_mut();
56                 ret
57         }
58 }
59 /// The sequence number of this update. Updates *must* be replayed in-order according to this
60 /// sequence number (and updates may panic if they are not). The update_id values are strictly
61 /// increasing and increase by one for each new update, with one exception specified below.
62 ///
63 /// This sequence number is also used to track up to which points updates which returned
64 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
65 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
66 ///
67 /// The only instance where update_id values are not strictly increasing is the case where we
68 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
69 /// its docs for more details.
70 ///
71 /// [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
72 #[no_mangle]
73 pub extern "C" fn ChannelMonitorUpdate_get_update_id(this_ptr: &ChannelMonitorUpdate) -> u64 {
74         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.update_id;
75         (*inner_val)
76 }
77 /// The sequence number of this update. Updates *must* be replayed in-order according to this
78 /// sequence number (and updates may panic if they are not). The update_id values are strictly
79 /// increasing and increase by one for each new update, with one exception specified below.
80 ///
81 /// This sequence number is also used to track up to which points updates which returned
82 /// ChannelMonitorUpdateErr::TemporaryFailure have been applied to all copies of a given
83 /// ChannelMonitor when ChannelManager::channel_monitor_updated is called.
84 ///
85 /// The only instance where update_id values are not strictly increasing is the case where we
86 /// allow post-force-close updates with a special update ID of [`CLOSED_CHANNEL_UPDATE_ID`]. See
87 /// its docs for more details.
88 ///
89 /// [`CLOSED_CHANNEL_UPDATE_ID`]: constant.CLOSED_CHANNEL_UPDATE_ID.html
90 #[no_mangle]
91 pub extern "C" fn ChannelMonitorUpdate_set_update_id(this_ptr: &mut ChannelMonitorUpdate, mut val: u64) {
92         unsafe { &mut *this_ptr.inner }.update_id = val;
93 }
94 impl Clone for ChannelMonitorUpdate {
95         fn clone(&self) -> Self {
96                 Self {
97                         inner: if <*mut nativeChannelMonitorUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
98                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
99                         is_owned: true,
100                 }
101         }
102 }
103 #[allow(unused)]
104 /// Used only if an object of this type is returned as a trait impl by a method
105 pub(crate) extern "C" fn ChannelMonitorUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
106         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelMonitorUpdate)).clone() })) as *mut c_void
107 }
108 #[no_mangle]
109 pub extern "C" fn ChannelMonitorUpdate_clone(orig: &ChannelMonitorUpdate) -> ChannelMonitorUpdate {
110         orig.clone()
111 }
112
113 #[no_mangle]
114 pub static CLOSED_CHANNEL_UPDATE_ID: u64 = lightning::chain::channelmonitor::CLOSED_CHANNEL_UPDATE_ID;
115 #[no_mangle]
116 pub extern "C" fn ChannelMonitorUpdate_write(obj: &ChannelMonitorUpdate) -> crate::c_types::derived::CVec_u8Z {
117         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
118 }
119 #[no_mangle]
120 pub(crate) extern "C" fn ChannelMonitorUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
121         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitorUpdate) })
122 }
123 #[no_mangle]
124 pub extern "C" fn ChannelMonitorUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelMonitorUpdateDecodeErrorZ {
125         let res = crate::c_types::deserialize_obj(ser);
126         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::ChannelMonitorUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
127         local_res
128 }
129 /// An error enum representing a failure to persist a channel monitor update.
130 #[must_use]
131 #[derive(Clone)]
132 #[repr(C)]
133 pub enum ChannelMonitorUpdateErr {
134         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
135         /// our state failed, but is expected to succeed at some point in the future).
136         ///
137         /// Such a failure will \"freeze\" a channel, preventing us from revoking old states or
138         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
139         /// have been successfully applied, ChannelManager::channel_monitor_updated can be used to
140         /// restore the channel to an operational state.
141         ///
142         /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
143         /// you return a TemporaryFailure you must ensure that it is written to disk safely before
144         /// writing out the latest ChannelManager state.
145         ///
146         /// Even when a channel has been \"frozen\" updates to the ChannelMonitor can continue to occur
147         /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
148         /// to claim it on this channel) and those updates must be applied wherever they can be. At
149         /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
150         /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
151         /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
152         /// been \"frozen\".
153         ///
154         /// Note that even if updates made after TemporaryFailure succeed you must still call
155         /// channel_monitor_updated to ensure you have the latest monitor and re-enable normal channel
156         /// operation.
157         ///
158         /// Note that the update being processed here will not be replayed for you when you call
159         /// ChannelManager::channel_monitor_updated, so you must store the update itself along
160         /// with the persisted ChannelMonitor on your own local disk prior to returning a
161         /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
162         /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
163         /// reload-time.
164         ///
165         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
166         /// remote location (with local copies persisted immediately), it is anticipated that all
167         /// updates will return TemporaryFailure until the remote copies could be updated.
168         TemporaryFailure,
169         /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
170         /// different watchtower and cannot update with all watchtowers that were previously informed
171         /// of this channel).
172         ///
173         /// At reception of this error, ChannelManager will force-close the channel and return at
174         /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
175         /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
176         /// update must be rejected.
177         ///
178         /// This failure may also signal a failure to update the local persisted copy of one of
179         /// the channel monitor instance.
180         ///
181         /// Note that even when you fail a holder commitment transaction update, you must store the
182         /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
183         /// broadcasts it (e.g distributed channel-monitor deployment)
184         ///
185         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
186         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
187         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
188         /// lagging behind on block processing.
189         PermanentFailure,
190 }
191 use lightning::chain::channelmonitor::ChannelMonitorUpdateErr as nativeChannelMonitorUpdateErr;
192 impl ChannelMonitorUpdateErr {
193         #[allow(unused)]
194         pub(crate) fn to_native(&self) -> nativeChannelMonitorUpdateErr {
195                 match self {
196                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
197                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
198                 }
199         }
200         #[allow(unused)]
201         pub(crate) fn into_native(self) -> nativeChannelMonitorUpdateErr {
202                 match self {
203                         ChannelMonitorUpdateErr::TemporaryFailure => nativeChannelMonitorUpdateErr::TemporaryFailure,
204                         ChannelMonitorUpdateErr::PermanentFailure => nativeChannelMonitorUpdateErr::PermanentFailure,
205                 }
206         }
207         #[allow(unused)]
208         pub(crate) fn from_native(native: &nativeChannelMonitorUpdateErr) -> Self {
209                 match native {
210                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
211                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
212                 }
213         }
214         #[allow(unused)]
215         pub(crate) fn native_into(native: nativeChannelMonitorUpdateErr) -> Self {
216                 match native {
217                         nativeChannelMonitorUpdateErr::TemporaryFailure => ChannelMonitorUpdateErr::TemporaryFailure,
218                         nativeChannelMonitorUpdateErr::PermanentFailure => ChannelMonitorUpdateErr::PermanentFailure,
219                 }
220         }
221 }
222 #[no_mangle]
223 pub extern "C" fn ChannelMonitorUpdateErr_clone(orig: &ChannelMonitorUpdateErr) -> ChannelMonitorUpdateErr {
224         orig.clone()
225 }
226
227 use lightning::chain::channelmonitor::MonitorUpdateError as nativeMonitorUpdateErrorImport;
228 type nativeMonitorUpdateError = nativeMonitorUpdateErrorImport;
229
230 /// General Err type for ChannelMonitor actions. Generally, this implies that the data provided is
231 /// inconsistent with the ChannelMonitor being called. eg for ChannelMonitor::update_monitor this
232 /// means you tried to update a monitor for a different channel or the ChannelMonitorUpdate was
233 /// corrupted.
234 /// Contains a developer-readable error message.
235 #[must_use]
236 #[repr(C)]
237 pub struct MonitorUpdateError {
238         /// Nearly everywhere, inner must be non-null, however in places where
239         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
240         pub inner: *mut nativeMonitorUpdateError,
241         pub is_owned: bool,
242 }
243
244 impl Drop for MonitorUpdateError {
245         fn drop(&mut self) {
246                 if self.is_owned && !<*mut nativeMonitorUpdateError>::is_null(self.inner) {
247                         let _ = unsafe { Box::from_raw(self.inner) };
248                 }
249         }
250 }
251 #[no_mangle]
252 pub extern "C" fn MonitorUpdateError_free(this_ptr: MonitorUpdateError) { }
253 #[allow(unused)]
254 /// Used only if an object of this type is returned as a trait impl by a method
255 extern "C" fn MonitorUpdateError_free_void(this_ptr: *mut c_void) {
256         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMonitorUpdateError); }
257 }
258 #[allow(unused)]
259 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
260 impl MonitorUpdateError {
261         pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateError {
262                 assert!(self.is_owned);
263                 let ret = self.inner;
264                 self.inner = std::ptr::null_mut();
265                 ret
266         }
267 }
268 impl Clone for MonitorUpdateError {
269         fn clone(&self) -> Self {
270                 Self {
271                         inner: if <*mut nativeMonitorUpdateError>::is_null(self.inner) { std::ptr::null_mut() } else {
272                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
273                         is_owned: true,
274                 }
275         }
276 }
277 #[allow(unused)]
278 /// Used only if an object of this type is returned as a trait impl by a method
279 pub(crate) extern "C" fn MonitorUpdateError_clone_void(this_ptr: *const c_void) -> *mut c_void {
280         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMonitorUpdateError)).clone() })) as *mut c_void
281 }
282 #[no_mangle]
283 pub extern "C" fn MonitorUpdateError_clone(orig: &MonitorUpdateError) -> MonitorUpdateError {
284         orig.clone()
285 }
286 /// An event to be processed by the ChannelManager.
287 #[must_use]
288 #[derive(Clone)]
289 #[repr(C)]
290 pub enum MonitorEvent {
291         /// A monitor event containing an HTLCUpdate.
292         HTLCEvent(crate::chain::channelmonitor::HTLCUpdate),
293         /// A monitor event that the Channel's commitment transaction was broadcasted.
294         CommitmentTxBroadcasted(crate::chain::transaction::OutPoint),
295 }
296 use lightning::chain::channelmonitor::MonitorEvent as nativeMonitorEvent;
297 impl MonitorEvent {
298         #[allow(unused)]
299         pub(crate) fn to_native(&self) -> nativeMonitorEvent {
300                 match self {
301                         MonitorEvent::HTLCEvent (ref a, ) => {
302                                 let mut a_nonref = (*a).clone();
303                                 nativeMonitorEvent::HTLCEvent (
304                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
305                                 )
306                         },
307                         MonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
308                                 let mut a_nonref = (*a).clone();
309                                 nativeMonitorEvent::CommitmentTxBroadcasted (
310                                         *unsafe { Box::from_raw(a_nonref.take_inner()) },
311                                 )
312                         },
313                 }
314         }
315         #[allow(unused)]
316         pub(crate) fn into_native(self) -> nativeMonitorEvent {
317                 match self {
318                         MonitorEvent::HTLCEvent (mut a, ) => {
319                                 nativeMonitorEvent::HTLCEvent (
320                                         *unsafe { Box::from_raw(a.take_inner()) },
321                                 )
322                         },
323                         MonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
324                                 nativeMonitorEvent::CommitmentTxBroadcasted (
325                                         *unsafe { Box::from_raw(a.take_inner()) },
326                                 )
327                         },
328                 }
329         }
330         #[allow(unused)]
331         pub(crate) fn from_native(native: &nativeMonitorEvent) -> Self {
332                 match native {
333                         nativeMonitorEvent::HTLCEvent (ref a, ) => {
334                                 let mut a_nonref = (*a).clone();
335                                 MonitorEvent::HTLCEvent (
336                                         crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
337                                 )
338                         },
339                         nativeMonitorEvent::CommitmentTxBroadcasted (ref a, ) => {
340                                 let mut a_nonref = (*a).clone();
341                                 MonitorEvent::CommitmentTxBroadcasted (
342                                         crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a_nonref)), is_owned: true },
343                                 )
344                         },
345                 }
346         }
347         #[allow(unused)]
348         pub(crate) fn native_into(native: nativeMonitorEvent) -> Self {
349                 match native {
350                         nativeMonitorEvent::HTLCEvent (mut a, ) => {
351                                 MonitorEvent::HTLCEvent (
352                                         crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(a)), is_owned: true },
353                                 )
354                         },
355                         nativeMonitorEvent::CommitmentTxBroadcasted (mut a, ) => {
356                                 MonitorEvent::CommitmentTxBroadcasted (
357                                         crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(a)), is_owned: true },
358                                 )
359                         },
360                 }
361         }
362 }
363 #[no_mangle]
364 pub extern "C" fn MonitorEvent_free(this_ptr: MonitorEvent) { }
365 #[no_mangle]
366 pub extern "C" fn MonitorEvent_clone(orig: &MonitorEvent) -> MonitorEvent {
367         orig.clone()
368 }
369
370 use lightning::chain::channelmonitor::HTLCUpdate as nativeHTLCUpdateImport;
371 type nativeHTLCUpdate = nativeHTLCUpdateImport;
372
373 /// Simple structure sent back by `chain::Watch` when an HTLC from a forward channel is detected on
374 /// chain. Used to update the corresponding HTLC in the backward channel. Failing to pass the
375 /// preimage claim backward will lead to loss of funds.
376 ///
377 /// [`chain::Watch`]: ../trait.Watch.html
378 #[must_use]
379 #[repr(C)]
380 pub struct HTLCUpdate {
381         /// Nearly everywhere, inner must be non-null, however in places where
382         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
383         pub inner: *mut nativeHTLCUpdate,
384         pub is_owned: bool,
385 }
386
387 impl Drop for HTLCUpdate {
388         fn drop(&mut self) {
389                 if self.is_owned && !<*mut nativeHTLCUpdate>::is_null(self.inner) {
390                         let _ = unsafe { Box::from_raw(self.inner) };
391                 }
392         }
393 }
394 #[no_mangle]
395 pub extern "C" fn HTLCUpdate_free(this_ptr: HTLCUpdate) { }
396 #[allow(unused)]
397 /// Used only if an object of this type is returned as a trait impl by a method
398 extern "C" fn HTLCUpdate_free_void(this_ptr: *mut c_void) {
399         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeHTLCUpdate); }
400 }
401 #[allow(unused)]
402 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
403 impl HTLCUpdate {
404         pub(crate) fn take_inner(mut self) -> *mut nativeHTLCUpdate {
405                 assert!(self.is_owned);
406                 let ret = self.inner;
407                 self.inner = std::ptr::null_mut();
408                 ret
409         }
410 }
411 impl Clone for HTLCUpdate {
412         fn clone(&self) -> Self {
413                 Self {
414                         inner: if <*mut nativeHTLCUpdate>::is_null(self.inner) { std::ptr::null_mut() } else {
415                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
416                         is_owned: true,
417                 }
418         }
419 }
420 #[allow(unused)]
421 /// Used only if an object of this type is returned as a trait impl by a method
422 pub(crate) extern "C" fn HTLCUpdate_clone_void(this_ptr: *const c_void) -> *mut c_void {
423         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeHTLCUpdate)).clone() })) as *mut c_void
424 }
425 #[no_mangle]
426 pub extern "C" fn HTLCUpdate_clone(orig: &HTLCUpdate) -> HTLCUpdate {
427         orig.clone()
428 }
429 #[no_mangle]
430 pub extern "C" fn HTLCUpdate_write(obj: &HTLCUpdate) -> crate::c_types::derived::CVec_u8Z {
431         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
432 }
433 #[no_mangle]
434 pub(crate) extern "C" fn HTLCUpdate_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
435         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeHTLCUpdate) })
436 }
437 #[no_mangle]
438 pub extern "C" fn HTLCUpdate_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_HTLCUpdateDecodeErrorZ {
439         let res = crate::c_types::deserialize_obj(ser);
440         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::chain::channelmonitor::HTLCUpdate { inner: Box::into_raw(Box::new(o)), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
441         local_res
442 }
443
444 use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport;
445 type nativeChannelMonitor = nativeChannelMonitorImport<crate::chain::keysinterface::Sign>;
446
447 /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates
448 /// on-chain transactions to ensure no loss of funds occurs.
449 ///
450 /// You MUST ensure that no ChannelMonitors for a given channel anywhere contain out-of-date
451 /// information and are actively monitoring the chain.
452 ///
453 /// Pending Events or updated HTLCs which have not yet been read out by
454 /// get_and_clear_pending_monitor_events or get_and_clear_pending_events are serialized to disk and
455 /// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
456 /// gotten are fully handled before re-serializing the new state.
457 ///
458 /// Note that the deserializer is only implemented for (BlockHash, ChannelMonitor), which
459 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
460 /// the \"reorg path\" (ie disconnecting blocks until you find a common ancestor from both the
461 /// returned block hash and the the current chain and then reconnecting blocks to get to the
462 /// best chain) upon deserializing the object!
463 #[must_use]
464 #[repr(C)]
465 pub struct ChannelMonitor {
466         /// Nearly everywhere, inner must be non-null, however in places where
467         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
468         pub inner: *mut nativeChannelMonitor,
469         pub is_owned: bool,
470 }
471
472 impl Drop for ChannelMonitor {
473         fn drop(&mut self) {
474                 if self.is_owned && !<*mut nativeChannelMonitor>::is_null(self.inner) {
475                         let _ = unsafe { Box::from_raw(self.inner) };
476                 }
477         }
478 }
479 #[no_mangle]
480 pub extern "C" fn ChannelMonitor_free(this_ptr: ChannelMonitor) { }
481 #[allow(unused)]
482 /// Used only if an object of this type is returned as a trait impl by a method
483 extern "C" fn ChannelMonitor_free_void(this_ptr: *mut c_void) {
484         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelMonitor); }
485 }
486 #[allow(unused)]
487 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
488 impl ChannelMonitor {
489         pub(crate) fn take_inner(mut self) -> *mut nativeChannelMonitor {
490                 assert!(self.is_owned);
491                 let ret = self.inner;
492                 self.inner = std::ptr::null_mut();
493                 ret
494         }
495 }
496 #[no_mangle]
497 pub extern "C" fn ChannelMonitor_write(obj: &ChannelMonitor) -> crate::c_types::derived::CVec_u8Z {
498         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
499 }
500 #[no_mangle]
501 pub(crate) extern "C" fn ChannelMonitor_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
502         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelMonitor) })
503 }
504 /// Updates a ChannelMonitor on the basis of some new information provided by the Channel
505 /// itself.
506 ///
507 /// panics if the given update is not the next update by update_id.
508 #[must_use]
509 #[no_mangle]
510 pub extern "C" fn ChannelMonitor_update_monitor(this_arg: &ChannelMonitor, updates: &crate::chain::channelmonitor::ChannelMonitorUpdate, broadcaster: &crate::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::chain::chaininterface::FeeEstimator, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CResult_NoneMonitorUpdateErrorZ {
511         let mut ret = unsafe { &*this_arg.inner }.update_monitor(unsafe { &*updates.inner }, broadcaster, fee_estimator, logger);
512         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::chain::channelmonitor::MonitorUpdateError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
513         local_ret
514 }
515
516 /// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
517 /// ChannelMonitor.
518 #[must_use]
519 #[no_mangle]
520 pub extern "C" fn ChannelMonitor_get_latest_update_id(this_arg: &ChannelMonitor) -> u64 {
521         let mut ret = unsafe { &*this_arg.inner }.get_latest_update_id();
522         ret
523 }
524
525 /// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
526 #[must_use]
527 #[no_mangle]
528 pub extern "C" fn ChannelMonitor_get_funding_txo(this_arg: &ChannelMonitor) -> crate::c_types::derived::C2Tuple_OutPointScriptZ {
529         let mut ret = unsafe { &*this_arg.inner }.get_funding_txo();
530         let (mut orig_ret_0, mut orig_ret_1) = ret; let mut local_ret = (crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(orig_ret_0)), is_owned: true }, orig_ret_1.into_bytes().into()).into();
531         local_ret
532 }
533
534 /// Get the list of HTLCs who's status has been updated on chain. This should be called by
535 /// ChannelManager via [`chain::Watch::release_pending_monitor_events`].
536 ///
537 /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
538 #[must_use]
539 #[no_mangle]
540 pub extern "C" fn ChannelMonitor_get_and_clear_pending_monitor_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_MonitorEventZ {
541         let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_monitor_events();
542         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::chain::channelmonitor::MonitorEvent::native_into(item) }); };
543         local_ret.into()
544 }
545
546 /// Gets the list of pending events which were generated by previous actions, clearing the list
547 /// in the process.
548 ///
549 /// This is called by ChainMonitor::get_and_clear_pending_events() and is equivalent to
550 /// EventsProvider::get_and_clear_pending_events() except that it requires &mut self as we do
551 /// no internal locking in ChannelMonitors.
552 #[must_use]
553 #[no_mangle]
554 pub extern "C" fn ChannelMonitor_get_and_clear_pending_events(this_arg: &ChannelMonitor) -> crate::c_types::derived::CVec_EventZ {
555         let mut ret = unsafe { &*this_arg.inner }.get_and_clear_pending_events();
556         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
557         local_ret.into()
558 }
559
560 /// Used by ChannelManager deserialization to broadcast the latest holder state if its copy of
561 /// the Channel was out-of-date. You may use it to get a broadcastable holder toxic tx in case of
562 /// fallen-behind, i.e when receiving a channel_reestablish with a proof that our counterparty side knows
563 /// a higher revocation secret than the holder commitment number we are aware of. Broadcasting these
564 /// transactions are UNSAFE, as they allow counterparty side to punish you. Nevertheless you may want to
565 /// broadcast them if counterparty don't close channel with his higher commitment transaction after a
566 /// substantial amount of time (a month or even a year) to get back funds. Best may be to contact
567 /// out-of-band the other node operator to coordinate with him if option is available to you.
568 /// In any-case, choice is up to the user.
569 #[must_use]
570 #[no_mangle]
571 pub extern "C" fn ChannelMonitor_get_latest_holder_commitment_txn(this_arg: &ChannelMonitor, logger: &crate::util::logger::Logger) -> crate::c_types::derived::CVec_TransactionZ {
572         let mut ret = unsafe { &*this_arg.inner }.get_latest_holder_commitment_txn(logger);
573         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let mut local_ret_0 = ::bitcoin::consensus::encode::serialize(&item); crate::c_types::Transaction::from_vec(local_ret_0) }); };
574         local_ret.into()
575 }
576
577 /// Processes transactions in a newly connected block, which may result in any of the following:
578 /// - update the monitor's state against resolved HTLCs
579 /// - punish the counterparty in the case of seeing a revoked commitment transaction
580 /// - force close the channel and claim/timeout incoming/outgoing HTLCs if near expiration
581 /// - detect settled outputs for later spending
582 /// - schedule and bump any in-flight claims
583 ///
584 /// Returns any new outputs to watch from `txdata`; after called, these are also included in
585 /// [`get_outputs_to_watch`].
586 ///
587 /// [`get_outputs_to_watch`]: #method.get_outputs_to_watch
588 #[must_use]
589 #[no_mangle]
590 pub extern "C" fn ChannelMonitor_block_connected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32, mut broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut logger: crate::util::logger::Logger) -> crate::c_types::derived::CVec_C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZZ {
591         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 }); };
592         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);
593         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 }); };
594         local_ret.into()
595 }
596
597 /// Determines if the disconnected block contained any transactions of interest and updates
598 /// appropriately.
599 #[no_mangle]
600 pub extern "C" fn ChannelMonitor_block_disconnected(this_arg: &ChannelMonitor, header: *const [u8; 80], mut height: u32, mut broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut logger: crate::util::logger::Logger) {
601         unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, broadcaster, fee_estimator, logger)
602 }
603
604 /// `Persist` defines behavior for persisting channel monitors: this could mean
605 /// writing once to disk, and/or uploading to one or more backup services.
606 ///
607 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
608 /// to disk/backups. And, on every update, you **must** persist either the
609 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
610 /// of situations such as revoking a transaction, then crashing before this
611 /// revocation can be persisted, then unintentionally broadcasting a revoked
612 /// transaction and losing money. This is a risk because previous channel states
613 /// are toxic, so it's important that whatever channel state is persisted is
614 /// kept up-to-date.
615 #[repr(C)]
616 pub struct Persist {
617         pub this_arg: *mut c_void,
618         /// Persist a new channel's data. The data can be stored any way you want, but
619         /// the identifier provided by Rust-Lightning is the channel's outpoint (and
620         /// it is up to you to maintain a correct mapping between the outpoint and the
621         /// stored channel data). Note that you **must** persist every new monitor to
622         /// disk. See the `Persist` trait documentation for more details.
623         ///
624         /// See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
625         /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
626         ///
627         /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
628         /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
629         #[must_use]
630         pub persist_new_channel: extern "C" fn (this_arg: *const c_void, id: crate::chain::transaction::OutPoint, data: &crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
631         /// Update one channel's data. The provided `ChannelMonitor` has already
632         /// applied the given update.
633         ///
634         /// Note that on every update, you **must** persist either the
635         /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
636         /// the `Persist` trait documentation for more details.
637         ///
638         /// If an implementer chooses to persist the updates only, they need to make
639         /// sure that all the updates are applied to the `ChannelMonitors` *before*
640         /// the set of channel monitors is given to the `ChannelManager`
641         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
642         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
643         /// persisted, then there is no need to persist individual updates.
644         ///
645         /// Note that there could be a performance tradeoff between persisting complete
646         /// channel monitors on every update vs. persisting only updates and applying
647         /// them in batches. The size of each monitor grows `O(number of state updates)`
648         /// whereas updates are small and `O(1)`.
649         ///
650         /// See [`ChannelMonitor::serialize_for_disk`] for writing out a `ChannelMonitor`,
651         /// [`ChannelMonitorUpdate::write`] for writing out an update, and
652         /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
653         ///
654         /// [`ChannelMonitor::update_monitor`]: struct.ChannelMonitor.html#impl-1
655         /// [`ChannelMonitor::serialize_for_disk`]: struct.ChannelMonitor.html#method.serialize_for_disk
656         /// [`ChannelMonitorUpdate::write`]: struct.ChannelMonitorUpdate.html#method.write
657         /// [`ChannelMonitorUpdateErr`]: enum.ChannelMonitorUpdateErr.html
658         #[must_use]
659         pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, id: crate::chain::transaction::OutPoint, update: &crate::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ,
660         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
661 }
662 unsafe impl Send for Persist {}
663 unsafe impl Sync for Persist {}
664
665 use lightning::chain::channelmonitor::Persist as rustPersist;
666 impl rustPersist<crate::chain::keysinterface::Sign> for Persist {
667         fn persist_new_channel(&self, id: lightning::chain::transaction::OutPoint, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
668                 let mut ret = (self.persist_new_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
669                 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() })};
670                 local_ret
671         }
672         fn update_persisted_channel(&self, id: lightning::chain::transaction::OutPoint, update: &lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>) -> Result<(), lightning::chain::channelmonitor::ChannelMonitorUpdateErr> {
673                 let mut ret = (self.update_persisted_channel)(self.this_arg, crate::chain::transaction::OutPoint { inner: Box::into_raw(Box::new(id)), is_owned: true }, &crate::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (update as *const _) as *mut _ }, is_owned: false }, &crate::chain::channelmonitor::ChannelMonitor { inner: unsafe { (data as *const _) as *mut _ }, is_owned: false });
674                 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() })};
675                 local_ret
676         }
677 }
678
679 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
680 // directly as a Deref trait in higher-level structs:
681 impl std::ops::Deref for Persist {
682         type Target = Self;
683         fn deref(&self) -> &Self {
684                 self
685         }
686 }
687 /// Calls the free function if one is set
688 #[no_mangle]
689 pub extern "C" fn Persist_free(this_ptr: Persist) { }
690 impl Drop for Persist {
691         fn drop(&mut self) {
692                 if let Some(f) = self.free {
693                         f(self.this_arg);
694                 }
695         }
696 }
697 #[no_mangle]
698 pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ {
699         let arg_conv = arg;
700         let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor<crate::chain::keysinterface::Sign>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
701         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: orig_res_0_0.into_inner() }, crate::chain::channelmonitor::ChannelMonitor { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
702         local_res
703 }