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