Update auto-generated bindings to LDK 0.0.118
[ldk-c-bindings] / lightning-c-bindings / src / lightning / chain / chainmonitor.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 //! Logic to connect off-chain channel management with on-chain transaction monitoring.
10 //!
11 //! [`ChainMonitor`] is an implementation of [`chain::Watch`] used both to process blocks and to
12 //! update [`ChannelMonitor`]s accordingly. If any on-chain events need further processing, it will
13 //! make those available as [`MonitorEvent`]s to be consumed.
14 //!
15 //! [`ChainMonitor`] is parameterized by an optional chain source, which must implement the
16 //! [`chain::Filter`] trait. This provides a mechanism to signal new relevant outputs back to light
17 //! clients, such that transactions spending those outputs are included in block data.
18 //!
19 //! [`ChainMonitor`] may be used directly to monitor channels locally or as a part of a distributed
20 //! setup to monitor channels remotely. In the latter case, a custom [`chain::Watch`] implementation
21 //! would be responsible for routing each update to a remote server and for retrieving monitor
22 //! events. The remote server would make use of [`ChainMonitor`] for block processing and for
23 //! servicing [`ChannelMonitor`] updates from the client.
24
25 use alloc::str::FromStr;
26 use alloc::string::String;
27 use core::ffi::c_void;
28 use core::convert::Infallible;
29 use bitcoin::hashes::Hash;
30 use crate::c_types::*;
31 #[cfg(feature="no-std")]
32 use alloc::{vec::Vec, boxed::Box};
33
34 mod update_origin {
35
36 use alloc::str::FromStr;
37 use alloc::string::String;
38 use core::ffi::c_void;
39 use core::convert::Infallible;
40 use bitcoin::hashes::Hash;
41 use crate::c_types::*;
42 #[cfg(feature="no-std")]
43 use alloc::{vec::Vec, boxed::Box};
44
45 }
46
47 use lightning::chain::chainmonitor::MonitorUpdateId as nativeMonitorUpdateIdImport;
48 pub(crate) type nativeMonitorUpdateId = nativeMonitorUpdateIdImport;
49
50 /// An opaque identifier describing a specific [`Persist`] method call.
51 #[must_use]
52 #[repr(C)]
53 pub struct MonitorUpdateId {
54         /// A pointer to the opaque Rust object.
55
56         /// Nearly everywhere, inner must be non-null, however in places where
57         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
58         pub inner: *mut nativeMonitorUpdateId,
59         /// Indicates that this is the only struct which contains the same pointer.
60
61         /// Rust functions which take ownership of an object provided via an argument require
62         /// this to be true and invalidate the object pointed to by inner.
63         pub is_owned: bool,
64 }
65
66 impl Drop for MonitorUpdateId {
67         fn drop(&mut self) {
68                 if self.is_owned && !<*mut nativeMonitorUpdateId>::is_null(self.inner) {
69                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
70                 }
71         }
72 }
73 /// Frees any resources used by the MonitorUpdateId, if is_owned is set and inner is non-NULL.
74 #[no_mangle]
75 pub extern "C" fn MonitorUpdateId_free(this_obj: MonitorUpdateId) { }
76 #[allow(unused)]
77 /// Used only if an object of this type is returned as a trait impl by a method
78 pub(crate) extern "C" fn MonitorUpdateId_free_void(this_ptr: *mut c_void) {
79         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMonitorUpdateId) };
80 }
81 #[allow(unused)]
82 impl MonitorUpdateId {
83         pub(crate) fn get_native_ref(&self) -> &'static nativeMonitorUpdateId {
84                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
85         }
86         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMonitorUpdateId {
87                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
88         }
89         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
90         pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdateId {
91                 assert!(self.is_owned);
92                 let ret = ObjOps::untweak_ptr(self.inner);
93                 self.inner = core::ptr::null_mut();
94                 ret
95         }
96 }
97 impl Clone for MonitorUpdateId {
98         fn clone(&self) -> Self {
99                 Self {
100                         inner: if <*mut nativeMonitorUpdateId>::is_null(self.inner) { core::ptr::null_mut() } else {
101                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
102                         is_owned: true,
103                 }
104         }
105 }
106 #[allow(unused)]
107 /// Used only if an object of this type is returned as a trait impl by a method
108 pub(crate) extern "C" fn MonitorUpdateId_clone_void(this_ptr: *const c_void) -> *mut c_void {
109         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeMonitorUpdateId)).clone() })) as *mut c_void
110 }
111 #[no_mangle]
112 /// Creates a copy of the MonitorUpdateId
113 pub extern "C" fn MonitorUpdateId_clone(orig: &MonitorUpdateId) -> MonitorUpdateId {
114         orig.clone()
115 }
116 /// Generates a non-cryptographic 64-bit hash of the MonitorUpdateId.
117 #[no_mangle]
118 pub extern "C" fn MonitorUpdateId_hash(o: &MonitorUpdateId) -> u64 {
119         if o.inner.is_null() { return 0; }
120         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
121         #[allow(deprecated)]
122         let mut hasher = core::hash::SipHasher::new();
123         core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
124         core::hash::Hasher::finish(&hasher)
125 }
126 /// Checks if two MonitorUpdateIds contain equal inner contents.
127 /// This ignores pointers and is_owned flags and looks at the values in fields.
128 /// Two objects with NULL inner values will be considered "equal" here.
129 #[no_mangle]
130 pub extern "C" fn MonitorUpdateId_eq(a: &MonitorUpdateId, b: &MonitorUpdateId) -> bool {
131         if a.inner == b.inner { return true; }
132         if a.inner.is_null() || b.inner.is_null() { return false; }
133         if a.get_native_ref() == b.get_native_ref() { true } else { false }
134 }
135 /// `Persist` defines behavior for persisting channel monitors: this could mean
136 /// writing once to disk, and/or uploading to one or more backup services.
137 ///
138 /// Persistence can happen in one of two ways - synchronously completing before the trait method
139 /// calls return or asynchronously in the background.
140 ///
141 /// # For those implementing synchronous persistence
142 ///
143 ///  * If persistence completes fully (including any relevant `fsync()` calls), the implementation
144 ///    should return [`ChannelMonitorUpdateStatus::Completed`], indicating normal channel operation
145 ///    should continue.
146 ///
147 ///  * If persistence fails for some reason, implementations should consider returning
148 ///    [`ChannelMonitorUpdateStatus::InProgress`] and retry all pending persistence operations in
149 ///    the background with [`ChainMonitor::list_pending_monitor_updates`] and
150 ///    [`ChainMonitor::get_monitor`].
151 ///
152 ///    Once a full [`ChannelMonitor`] has been persisted, all pending updates for that channel can
153 ///    be marked as complete via [`ChainMonitor::channel_monitor_updated`].
154 ///
155 ///    If at some point no further progress can be made towards persisting the pending updates, the
156 ///    node should simply shut down.
157 ///
158 ///  * If the persistence has failed and cannot be retried further (e.g. because of an outage),
159 ///    [`ChannelMonitorUpdateStatus::UnrecoverableError`] can be used, though this will result in
160 ///    an immediate panic and future operations in LDK generally failing.
161 ///
162 /// # For those implementing asynchronous persistence
163 ///
164 ///  All calls should generally spawn a background task and immediately return
165 ///  [`ChannelMonitorUpdateStatus::InProgress`]. Once the update completes,
166 ///  [`ChainMonitor::channel_monitor_updated`] should be called with the corresponding
167 ///  [`MonitorUpdateId`].
168 ///
169 ///  Note that unlike the direct [`chain::Watch`] interface,
170 ///  [`ChainMonitor::channel_monitor_updated`] must be called once for *each* update which occurs.
171 ///
172 ///  If at some point no further progress can be made towards persisting a pending update, the node
173 ///  should simply shut down. Until then, the background task should either loop indefinitely, or
174 ///  persistence should be regularly retried with [`ChainMonitor::list_pending_monitor_updates`]
175 ///  and [`ChainMonitor::get_monitor`] (note that if a full monitor is persisted all pending
176 ///  monitor updates may be marked completed).
177 ///
178 /// # Using remote watchtowers
179 ///
180 /// Watchtowers may be updated as a part of an implementation of this trait, utilizing the async
181 /// update process described above while the watchtower is being updated. The following methods are
182 /// provided for bulding transactions for a watchtower:
183 /// [`ChannelMonitor::initial_counterparty_commitment_tx`],
184 /// [`ChannelMonitor::counterparty_commitment_txs_from_update`],
185 /// [`ChannelMonitor::sign_to_local_justice_tx`], [`TrustedCommitmentTransaction::revokeable_output_index`],
186 /// [`TrustedCommitmentTransaction::build_to_local_justice_tx`].
187 ///
188 /// [`TrustedCommitmentTransaction::revokeable_output_index`]: crate::ln::chan_utils::TrustedCommitmentTransaction::revokeable_output_index
189 /// [`TrustedCommitmentTransaction::build_to_local_justice_tx`]: crate::ln::chan_utils::TrustedCommitmentTransaction::build_to_local_justice_tx
190 #[repr(C)]
191 pub struct Persist {
192         /// An opaque pointer which is passed to your function implementations as an argument.
193         /// This has no meaning in the LDK, and can be NULL or any other value.
194         pub this_arg: *mut c_void,
195         /// Persist a new channel's data in response to a [`chain::Watch::watch_channel`] call. This is
196         /// called by [`ChannelManager`] for new channels, or may be called directly, e.g. on startup.
197         ///
198         /// The data can be stored any way you want, but the identifier provided by LDK is the
199         /// channel's outpoint (and it is up to you to maintain a correct mapping between the outpoint
200         /// and the stored channel data). Note that you **must** persist every new monitor to disk.
201         ///
202         /// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
203         /// if you return [`ChannelMonitorUpdateStatus::InProgress`].
204         ///
205         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
206         /// and [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
207         ///
208         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
209         /// [`Writeable::write`]: crate::util::ser::Writeable::write
210         pub persist_new_channel: extern "C" fn (this_arg: *const c_void, channel_id: crate::lightning::chain::transaction::OutPoint, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus,
211         /// Update one channel's data. The provided [`ChannelMonitor`] has already applied the given
212         /// update.
213         ///
214         /// Note that on every update, you **must** persist either the [`ChannelMonitorUpdate`] or the
215         /// updated monitor itself to disk/backups. See the [`Persist`] trait documentation for more
216         /// details.
217         ///
218         /// During blockchain synchronization operations, and in some rare cases, this may be called with
219         /// no [`ChannelMonitorUpdate`], in which case the full [`ChannelMonitor`] needs to be persisted.
220         /// Note that after the full [`ChannelMonitor`] is persisted any previous
221         /// [`ChannelMonitorUpdate`]s which were persisted should be discarded - they can no longer be
222         /// applied to the persisted [`ChannelMonitor`] as they were already applied.
223         ///
224         /// If an implementer chooses to persist the updates only, they need to make
225         /// sure that all the updates are applied to the `ChannelMonitors` *before*
226         /// the set of channel monitors is given to the `ChannelManager`
227         /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
228         /// applying a monitor update to a monitor. If full `ChannelMonitors` are
229         /// persisted, then there is no need to persist individual updates.
230         ///
231         /// Note that there could be a performance tradeoff between persisting complete
232         /// channel monitors on every update vs. persisting only updates and applying
233         /// them in batches. The size of each monitor grows `O(number of state updates)`
234         /// whereas updates are small and `O(1)`.
235         ///
236         /// The `update_id` is used to identify this call to [`ChainMonitor::channel_monitor_updated`],
237         /// if you return [`ChannelMonitorUpdateStatus::InProgress`].
238         ///
239         /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
240         /// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
241         /// [`ChannelMonitorUpdateStatus`] for requirements when returning errors.
242         ///
243         /// [`Writeable::write`]: crate::util::ser::Writeable::write
244         ///
245         /// Note that update (or a relevant inner pointer) may be NULL or all-0s to represent None
246         pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, channel_id: crate::lightning::chain::transaction::OutPoint, update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus,
247         /// Frees any resources associated with this object given its this_arg pointer.
248         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
249         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
250 }
251 unsafe impl Send for Persist {}
252 unsafe impl Sync for Persist {}
253 #[allow(unused)]
254 pub(crate) fn Persist_clone_fields(orig: &Persist) -> Persist {
255         Persist {
256                 this_arg: orig.this_arg,
257                 persist_new_channel: Clone::clone(&orig.persist_new_channel),
258                 update_persisted_channel: Clone::clone(&orig.update_persisted_channel),
259                 free: Clone::clone(&orig.free),
260         }
261 }
262
263 use lightning::chain::chainmonitor::Persist as rustPersist;
264 impl rustPersist<crate::lightning::sign::WriteableEcdsaChannelSigner> for Persist {
265         fn persist_new_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::WriteableEcdsaChannelSigner>, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus {
266                 let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(channel_id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const lightning::chain::channelmonitor::ChannelMonitor<_, >) as *mut _) }, is_owned: false }, crate::lightning::chain::chainmonitor::MonitorUpdateId { inner: ObjOps::heap_alloc(update_id), is_owned: true });
267                 ret.into_native()
268         }
269         fn update_persisted_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut update: Option<&lightning::chain::channelmonitor::ChannelMonitorUpdate>, mut data: &lightning::chain::channelmonitor::ChannelMonitor<crate::lightning::sign::WriteableEcdsaChannelSigner>, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus {
270                 let mut local_update = crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (if update.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (update.unwrap()) }) } as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _ }, is_owned: false };
271                 let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(channel_id), is_owned: true }, local_update, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const lightning::chain::channelmonitor::ChannelMonitor<_, >) as *mut _) }, is_owned: false }, crate::lightning::chain::chainmonitor::MonitorUpdateId { inner: ObjOps::heap_alloc(update_id), is_owned: true });
272                 ret.into_native()
273         }
274 }
275
276 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
277 // directly as a Deref trait in higher-level structs:
278 impl core::ops::Deref for Persist {
279         type Target = Self;
280         fn deref(&self) -> &Self {
281                 self
282         }
283 }
284 impl core::ops::DerefMut for Persist {
285         fn deref_mut(&mut self) -> &mut Self {
286                 self
287         }
288 }
289 /// Calls the free function if one is set
290 #[no_mangle]
291 pub extern "C" fn Persist_free(this_ptr: Persist) { }
292 impl Drop for Persist {
293         fn drop(&mut self) {
294                 if let Some(f) = self.free {
295                         f(self.this_arg);
296                 }
297         }
298 }
299
300 use lightning::chain::chainmonitor::LockedChannelMonitor as nativeLockedChannelMonitorImport;
301 pub(crate) type nativeLockedChannelMonitor = nativeLockedChannelMonitorImport<'static, crate::lightning::sign::WriteableEcdsaChannelSigner>;
302
303 /// A read-only reference to a current ChannelMonitor.
304 ///
305 /// Note that this holds a mutex in [`ChainMonitor`] and may block other events until it is
306 /// released.
307 #[must_use]
308 #[repr(C)]
309 pub struct LockedChannelMonitor {
310         /// A pointer to the opaque Rust object.
311
312         /// Nearly everywhere, inner must be non-null, however in places where
313         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
314         pub inner: *mut nativeLockedChannelMonitor,
315         /// Indicates that this is the only struct which contains the same pointer.
316
317         /// Rust functions which take ownership of an object provided via an argument require
318         /// this to be true and invalidate the object pointed to by inner.
319         pub is_owned: bool,
320 }
321
322 impl Drop for LockedChannelMonitor {
323         fn drop(&mut self) {
324                 if self.is_owned && !<*mut nativeLockedChannelMonitor>::is_null(self.inner) {
325                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
326                 }
327         }
328 }
329 /// Frees any resources used by the LockedChannelMonitor, if is_owned is set and inner is non-NULL.
330 #[no_mangle]
331 pub extern "C" fn LockedChannelMonitor_free(this_obj: LockedChannelMonitor) { }
332 #[allow(unused)]
333 /// Used only if an object of this type is returned as a trait impl by a method
334 pub(crate) extern "C" fn LockedChannelMonitor_free_void(this_ptr: *mut c_void) {
335         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeLockedChannelMonitor) };
336 }
337 #[allow(unused)]
338 impl LockedChannelMonitor {
339         pub(crate) fn get_native_ref(&self) -> &'static nativeLockedChannelMonitor {
340                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
341         }
342         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeLockedChannelMonitor {
343                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
344         }
345         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
346         pub(crate) fn take_inner(mut self) -> *mut nativeLockedChannelMonitor {
347                 assert!(self.is_owned);
348                 let ret = ObjOps::untweak_ptr(self.inner);
349                 self.inner = core::ptr::null_mut();
350                 ret
351         }
352 }
353
354 use lightning::chain::chainmonitor::ChainMonitor as nativeChainMonitorImport;
355 pub(crate) type nativeChainMonitor = nativeChainMonitorImport<crate::lightning::sign::WriteableEcdsaChannelSigner, crate::lightning::chain::Filter, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger, crate::lightning::chain::chainmonitor::Persist>;
356
357 /// An implementation of [`chain::Watch`] for monitoring channels.
358 ///
359 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
360 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
361 /// or used independently to monitor channels remotely. See the [module-level documentation] for
362 /// details.
363 ///
364 /// Note that `ChainMonitor` should regularly trigger rebroadcasts/fee bumps of pending claims from
365 /// a force-closed channel. This is crucial in preventing certain classes of pinning attacks,
366 /// detecting substantial mempool feerate changes between blocks, and ensuring reliability if
367 /// broadcasting fails. We recommend invoking this every 30 seconds, or lower if running in an
368 /// environment with spotty connections, like on mobile.
369 ///
370 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
371 /// [module-level documentation]: crate::chain::chainmonitor
372 /// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
373 #[must_use]
374 #[repr(C)]
375 pub struct ChainMonitor {
376         /// A pointer to the opaque Rust object.
377
378         /// Nearly everywhere, inner must be non-null, however in places where
379         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
380         pub inner: *mut nativeChainMonitor,
381         /// Indicates that this is the only struct which contains the same pointer.
382
383         /// Rust functions which take ownership of an object provided via an argument require
384         /// this to be true and invalidate the object pointed to by inner.
385         pub is_owned: bool,
386 }
387
388 impl Drop for ChainMonitor {
389         fn drop(&mut self) {
390                 if self.is_owned && !<*mut nativeChainMonitor>::is_null(self.inner) {
391                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
392                 }
393         }
394 }
395 /// Frees any resources used by the ChainMonitor, if is_owned is set and inner is non-NULL.
396 #[no_mangle]
397 pub extern "C" fn ChainMonitor_free(this_obj: ChainMonitor) { }
398 #[allow(unused)]
399 /// Used only if an object of this type is returned as a trait impl by a method
400 pub(crate) extern "C" fn ChainMonitor_free_void(this_ptr: *mut c_void) {
401         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChainMonitor) };
402 }
403 #[allow(unused)]
404 impl ChainMonitor {
405         pub(crate) fn get_native_ref(&self) -> &'static nativeChainMonitor {
406                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
407         }
408         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainMonitor {
409                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
410         }
411         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
412         pub(crate) fn take_inner(mut self) -> *mut nativeChainMonitor {
413                 assert!(self.is_owned);
414                 let ret = ObjOps::untweak_ptr(self.inner);
415                 self.inner = core::ptr::null_mut();
416                 ret
417         }
418 }
419 /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
420 ///
421 /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
422 /// will call back to it indicating transactions and outputs of interest. This allows clients to
423 /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
424 /// always need to fetch full blocks absent another means for determining which blocks contain
425 /// transactions relevant to the watched channels.
426 #[must_use]
427 #[no_mangle]
428 pub extern "C" fn ChainMonitor_new(mut chain_source: crate::c_types::derived::COption_FilterZ, mut broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut feeest: crate::lightning::chain::chaininterface::FeeEstimator, mut persister: crate::lightning::chain::chainmonitor::Persist) -> crate::lightning::chain::chainmonitor::ChainMonitor {
429         let mut local_chain_source = { /*chain_source*/ let chain_source_opt = chain_source; if chain_source_opt.is_none() { None } else { Some({ { { chain_source_opt.take() } }})} };
430         let mut ret = lightning::chain::chainmonitor::ChainMonitor::new(local_chain_source, broadcaster, logger, feeest, persister);
431         crate::lightning::chain::chainmonitor::ChainMonitor { inner: ObjOps::heap_alloc(ret), is_owned: true }
432 }
433
434 /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
435 /// claims which are awaiting confirmation.
436 ///
437 /// Includes the balances from each [`ChannelMonitor`] *except* those included in
438 /// `ignored_channels`, allowing you to filter out balances from channels which are still open
439 /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
440 ///
441 /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
442 /// inclusion in the return value.
443 #[must_use]
444 #[no_mangle]
445 pub extern "C" fn ChainMonitor_get_claimable_balances(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor, mut ignored_channels: crate::c_types::derived::CVec_ChannelDetailsZ) -> crate::c_types::derived::CVec_BalanceZ {
446         let mut local_ignored_channels = Vec::new(); for mut item in ignored_channels.as_slice().iter() { local_ignored_channels.push( { item.get_native_ref() }); };
447         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_claimable_balances(&local_ignored_channels[..]);
448         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::Balance::native_into(item) }); };
449         local_ret.into()
450 }
451
452 /// Gets the [`LockedChannelMonitor`] for a given funding outpoint, returning an `Err` if no
453 /// such [`ChannelMonitor`] is currently being monitored for.
454 ///
455 /// Note that the result holds a mutex over our monitor set, and should not be held
456 /// indefinitely.
457 #[must_use]
458 #[no_mangle]
459 pub extern "C" fn ChainMonitor_get_monitor(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor, mut funding_txo: crate::lightning::chain::transaction::OutPoint) -> crate::c_types::derived::CResult_LockedChannelMonitorNoneZ {
460         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_monitor(*unsafe { Box::from_raw(funding_txo.take_inner()) });
461         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::chainmonitor::LockedChannelMonitor { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
462         local_ret
463 }
464
465 /// Lists the funding outpoint of each [`ChannelMonitor`] being monitored.
466 ///
467 /// Note that [`ChannelMonitor`]s are not removed when a channel is closed as they are always
468 /// monitoring for on-chain state resolutions.
469 #[must_use]
470 #[no_mangle]
471 pub extern "C" fn ChainMonitor_list_monitors(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor) -> crate::c_types::derived::CVec_OutPointZ {
472         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_monitors();
473         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
474         local_ret.into()
475 }
476
477 /// Lists the pending updates for each [`ChannelMonitor`] (by `OutPoint` being monitored).
478 #[must_use]
479 #[no_mangle]
480 pub extern "C" fn ChainMonitor_list_pending_monitor_updates(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor) -> crate::c_types::derived::CVec_C2Tuple_OutPointCVec_MonitorUpdateIdZZZ {
481         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_pending_monitor_updates();
482         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( { crate::lightning::chain::chainmonitor::MonitorUpdateId { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; let mut local_ret_0 = (crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(orig_ret_0_0), is_owned: true }, local_orig_ret_0_1.into()).into(); local_ret_0 }); };
483         local_ret.into()
484 }
485
486 /// Indicates the persistence of a [`ChannelMonitor`] has completed after
487 /// [`ChannelMonitorUpdateStatus::InProgress`] was returned from an update operation.
488 ///
489 /// Thus, the anticipated use is, at a high level:
490 ///  1) This [`ChainMonitor`] calls [`Persist::update_persisted_channel`] which stores the
491 ///     update to disk and begins updating any remote (e.g. watchtower/backup) copies,
492 ///     returning [`ChannelMonitorUpdateStatus::InProgress`],
493 ///  2) once all remote copies are updated, you call this function with the
494 ///     `completed_update_id` that completed, and once all pending updates have completed the
495 ///     channel will be re-enabled.
496 ///
497 /// Returns an [`APIError::APIMisuseError`] if `funding_txo` does not match any currently
498 /// registered [`ChannelMonitor`]s.
499 #[must_use]
500 #[no_mangle]
501 pub extern "C" fn ChainMonitor_channel_monitor_updated(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor, mut funding_txo: crate::lightning::chain::transaction::OutPoint, mut completed_update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
502         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_monitor_updated(*unsafe { Box::from_raw(funding_txo.take_inner()) }, *unsafe { Box::from_raw(completed_update_id.take_inner()) });
503         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::util::errors::APIError::native_into(e) }).into() };
504         local_ret
505 }
506
507 /// Gets a [`Future`] that completes when an event is available either via
508 /// [`chain::Watch::release_pending_monitor_events`] or
509 /// [`EventsProvider::process_pending_events`].
510 ///
511 /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
512 /// [`ChainMonitor`] and should instead register actions to be taken later.
513 ///
514 /// [`EventsProvider::process_pending_events`]: crate::events::EventsProvider::process_pending_events
515 #[must_use]
516 #[no_mangle]
517 pub extern "C" fn ChainMonitor_get_update_future(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor) -> crate::lightning::util::wakers::Future {
518         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_update_future();
519         crate::lightning::util::wakers::Future { inner: ObjOps::heap_alloc(ret), is_owned: true }
520 }
521
522 /// Triggers rebroadcasts/fee-bumps of pending claims from a force-closed channel. This is
523 /// crucial in preventing certain classes of pinning attacks, detecting substantial mempool
524 /// feerate changes between blocks, and ensuring reliability if broadcasting fails. We recommend
525 /// invoking this every 30 seconds, or lower if running in an environment with spotty
526 /// connections, like on mobile.
527 #[no_mangle]
528 pub extern "C" fn ChainMonitor_rebroadcast_pending_claims(this_arg: &crate::lightning::chain::chainmonitor::ChainMonitor) {
529         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.rebroadcast_pending_claims()
530 }
531
532 impl From<nativeChainMonitor> for crate::lightning::chain::Listen {
533         fn from(obj: nativeChainMonitor) -> Self {
534                 let rust_obj = crate::lightning::chain::chainmonitor::ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
535                 let mut ret = ChainMonitor_as_Listen(&rust_obj);
536                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
537                 core::mem::forget(rust_obj);
538                 ret.free = Some(ChainMonitor_free_void);
539                 ret
540         }
541 }
542 /// Constructs a new Listen which calls the relevant methods on this_arg.
543 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
544 #[no_mangle]
545 pub extern "C" fn ChainMonitor_as_Listen(this_arg: &ChainMonitor) -> crate::lightning::chain::Listen {
546         crate::lightning::chain::Listen {
547                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
548                 free: None,
549                 filtered_block_connected: ChainMonitor_Listen_filtered_block_connected,
550                 block_connected: ChainMonitor_Listen_block_connected,
551                 block_disconnected: ChainMonitor_Listen_block_disconnected,
552         }
553 }
554
555 extern "C" fn ChainMonitor_Listen_filtered_block_connected(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
556         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 }); };
557         <nativeChainMonitor as lightning::chain::Listen<>>::filtered_block_connected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
558 }
559 extern "C" fn ChainMonitor_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
560         <nativeChainMonitor as lightning::chain::Listen<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
561 }
562 extern "C" fn ChainMonitor_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
563         <nativeChainMonitor as lightning::chain::Listen<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
564 }
565
566 impl From<nativeChainMonitor> for crate::lightning::chain::Confirm {
567         fn from(obj: nativeChainMonitor) -> Self {
568                 let rust_obj = crate::lightning::chain::chainmonitor::ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
569                 let mut ret = ChainMonitor_as_Confirm(&rust_obj);
570                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
571                 core::mem::forget(rust_obj);
572                 ret.free = Some(ChainMonitor_free_void);
573                 ret
574         }
575 }
576 /// Constructs a new Confirm which calls the relevant methods on this_arg.
577 /// This copies the `inner` pointer in this_arg and thus the returned Confirm must be freed before this_arg is
578 #[no_mangle]
579 pub extern "C" fn ChainMonitor_as_Confirm(this_arg: &ChainMonitor) -> crate::lightning::chain::Confirm {
580         crate::lightning::chain::Confirm {
581                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
582                 free: None,
583                 transactions_confirmed: ChainMonitor_Confirm_transactions_confirmed,
584                 transaction_unconfirmed: ChainMonitor_Confirm_transaction_unconfirmed,
585                 best_block_updated: ChainMonitor_Confirm_best_block_updated,
586                 get_relevant_txids: ChainMonitor_Confirm_get_relevant_txids,
587         }
588 }
589
590 extern "C" fn ChainMonitor_Confirm_transactions_confirmed(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
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         <nativeChainMonitor as lightning::chain::Confirm<>>::transactions_confirmed(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
593 }
594 extern "C" fn ChainMonitor_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) {
595         <nativeChainMonitor as lightning::chain::Confirm<>>::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
596 }
597 extern "C" fn ChainMonitor_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
598         <nativeChainMonitor as lightning::chain::Confirm<>>::best_block_updated(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
599 }
600 #[must_use]
601 extern "C" fn ChainMonitor_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_ThirtyTwoBytesCOption_ThirtyTwoBytesZZZ {
602         let mut ret = <nativeChainMonitor as lightning::chain::Confirm<>>::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
603         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 = if orig_ret_0_1.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.unwrap().into_inner() } }) }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.into_inner() }, local_orig_ret_0_1).into(); local_ret_0 }); };
604         local_ret.into()
605 }
606
607 impl From<nativeChainMonitor> for crate::lightning::chain::Watch {
608         fn from(obj: nativeChainMonitor) -> Self {
609                 let rust_obj = crate::lightning::chain::chainmonitor::ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
610                 let mut ret = ChainMonitor_as_Watch(&rust_obj);
611                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
612                 core::mem::forget(rust_obj);
613                 ret.free = Some(ChainMonitor_free_void);
614                 ret
615         }
616 }
617 /// Constructs a new Watch which calls the relevant methods on this_arg.
618 /// This copies the `inner` pointer in this_arg and thus the returned Watch must be freed before this_arg is
619 #[no_mangle]
620 pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::lightning::chain::Watch {
621         crate::lightning::chain::Watch {
622                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
623                 free: None,
624                 watch_channel: ChainMonitor_Watch_watch_channel,
625                 update_channel: ChainMonitor_Watch_update_channel,
626                 release_pending_monitor_events: ChainMonitor_Watch_release_pending_monitor_events,
627         }
628 }
629
630 #[must_use]
631 extern "C" fn ChainMonitor_Watch_watch_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, mut monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_ChannelMonitorUpdateStatusNoneZ {
632         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::watch_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, *unsafe { Box::from_raw(monitor.take_inner()) });
633         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
634         local_ret
635 }
636 #[must_use]
637 extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus {
638         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::update_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, update.get_native_ref());
639         crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(ret)
640 }
641 #[must_use]
642 extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OutPointCVec_MonitorEventZPublicKeyZZ {
643         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::release_pending_monitor_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
644         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, mut orig_ret_0_2) = 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( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); }; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_none() { crate::c_types::PublicKey::null() } else {  { crate::c_types::PublicKey::from_rust(&(orig_ret_0_2.unwrap())) } }; let mut local_ret_0 = (crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(orig_ret_0_0), is_owned: true }, local_orig_ret_0_1.into(), local_orig_ret_0_2).into(); local_ret_0 }); };
645         local_ret.into()
646 }
647
648 impl From<nativeChainMonitor> for crate::lightning::events::EventsProvider {
649         fn from(obj: nativeChainMonitor) -> Self {
650                 let rust_obj = crate::lightning::chain::chainmonitor::ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
651                 let mut ret = ChainMonitor_as_EventsProvider(&rust_obj);
652                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
653                 core::mem::forget(rust_obj);
654                 ret.free = Some(ChainMonitor_free_void);
655                 ret
656         }
657 }
658 /// Constructs a new EventsProvider which calls the relevant methods on this_arg.
659 /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
660 #[no_mangle]
661 pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::lightning::events::EventsProvider {
662         crate::lightning::events::EventsProvider {
663                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
664                 free: None,
665                 process_pending_events: ChainMonitor_EventsProvider_process_pending_events,
666         }
667 }
668
669 extern "C" fn ChainMonitor_EventsProvider_process_pending_events(this_arg: *const c_void, mut handler: crate::lightning::events::EventHandler) {
670         <nativeChainMonitor as lightning::events::EventsProvider<>>::process_pending_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, handler)
671 }
672