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