Merge pull request #45 from TheBlueMatt/main
[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 std::str::FromStr;
26 use std::ffi::c_void;
27 use core::convert::Infallible;
28 use bitcoin::hashes::Hash;
29 use crate::c_types::*;
30
31
32 use lightning::chain::chainmonitor::ChainMonitor as nativeChainMonitorImport;
33 type nativeChainMonitor = nativeChainMonitorImport<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Filter, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger, crate::lightning::chain::channelmonitor::Persist>;
34
35 /// An implementation of [`chain::Watch`] for monitoring channels.
36 ///
37 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
38 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
39 /// or used independently to monitor channels remotely. See the [module-level documentation] for
40 /// details.
41 ///
42 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
43 /// [module-level documentation]: crate::chain::chainmonitor
44 #[must_use]
45 #[repr(C)]
46 pub struct ChainMonitor {
47         /// A pointer to the opaque Rust object.
48
49         /// Nearly everywhere, inner must be non-null, however in places where
50         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
51         pub inner: *mut nativeChainMonitor,
52         /// Indicates that this is the only struct which contains the same pointer.
53
54         /// Rust functions which take ownership of an object provided via an argument require
55         /// this to be true and invalidate the object pointed to by inner.
56         pub is_owned: bool,
57 }
58
59 impl Drop for ChainMonitor {
60         fn drop(&mut self) {
61                 if self.is_owned && !<*mut nativeChainMonitor>::is_null(self.inner) {
62                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
63                 }
64         }
65 }
66 /// Frees any resources used by the ChainMonitor, if is_owned is set and inner is non-NULL.
67 #[no_mangle]
68 pub extern "C" fn ChainMonitor_free(this_obj: ChainMonitor) { }
69 #[allow(unused)]
70 /// Used only if an object of this type is returned as a trait impl by a method
71 extern "C" fn ChainMonitor_free_void(this_ptr: *mut c_void) {
72         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainMonitor); }
73 }
74 #[allow(unused)]
75 impl ChainMonitor {
76         pub(crate) fn get_native_ref(&self) -> &'static nativeChainMonitor {
77                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
78         }
79         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainMonitor {
80                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
81         }
82         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
83         pub(crate) fn take_inner(mut self) -> *mut nativeChainMonitor {
84                 assert!(self.is_owned);
85                 let ret = ObjOps::untweak_ptr(self.inner);
86                 self.inner = std::ptr::null_mut();
87                 ret
88         }
89 }
90 /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
91 ///
92 /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
93 /// will call back to it indicating transactions and outputs of interest. This allows clients to
94 /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
95 /// always need to fetch full blocks absent another means for determining which blocks contain
96 /// transactions relevant to the watched channels.
97 #[must_use]
98 #[no_mangle]
99 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::channelmonitor::Persist) -> ChainMonitor {
100         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() }) } };
101         let mut ret = lightning::chain::chainmonitor::ChainMonitor::new(local_chain_source, broadcaster, logger, feeest, persister);
102         ChainMonitor { inner: ObjOps::heap_alloc(ret), is_owned: true }
103 }
104
105 /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
106 /// claims which are awaiting confirmation.
107 ///
108 /// Includes the balances from each [`ChannelMonitor`] *except* those included in
109 /// `ignored_channels`, allowing you to filter out balances from channels which are still open
110 /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
111 ///
112 /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
113 /// inclusion in the return value.
114 #[must_use]
115 #[no_mangle]
116 pub extern "C" fn ChainMonitor_get_claimable_balances(this_arg: &ChainMonitor, mut ignored_channels: crate::c_types::derived::CVec_ChannelDetailsZ) -> crate::c_types::derived::CVec_BalanceZ {
117         let mut local_ignored_channels = Vec::new(); for mut item in ignored_channels.as_slice().iter() { local_ignored_channels.push( { item.get_native_ref() }); };
118         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_claimable_balances(&local_ignored_channels[..]);
119         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::Balance::native_into(item) }); };
120         local_ret.into()
121 }
122
123 impl From<nativeChainMonitor> for crate::lightning::chain::Listen {
124         fn from(obj: nativeChainMonitor) -> Self {
125                 let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
126                 let mut ret = ChainMonitor_as_Listen(&rust_obj);
127                 // 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
128                 rust_obj.inner = std::ptr::null_mut();
129                 ret.free = Some(ChainMonitor_free_void);
130                 ret
131         }
132 }
133 /// Constructs a new Listen which calls the relevant methods on this_arg.
134 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
135 #[no_mangle]
136 pub extern "C" fn ChainMonitor_as_Listen(this_arg: &ChainMonitor) -> crate::lightning::chain::Listen {
137         crate::lightning::chain::Listen {
138                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
139                 free: None,
140                 block_connected: ChainMonitor_Listen_block_connected,
141                 block_disconnected: ChainMonitor_Listen_block_disconnected,
142         }
143 }
144
145 extern "C" fn ChainMonitor_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
146         <nativeChainMonitor as lightning::chain::Listen<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
147 }
148 extern "C" fn ChainMonitor_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
149         <nativeChainMonitor as lightning::chain::Listen<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
150 }
151
152 impl From<nativeChainMonitor> for crate::lightning::chain::Confirm {
153         fn from(obj: nativeChainMonitor) -> Self {
154                 let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
155                 let mut ret = ChainMonitor_as_Confirm(&rust_obj);
156                 // 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
157                 rust_obj.inner = std::ptr::null_mut();
158                 ret.free = Some(ChainMonitor_free_void);
159                 ret
160         }
161 }
162 /// Constructs a new Confirm which calls the relevant methods on this_arg.
163 /// This copies the `inner` pointer in this_arg and thus the returned Confirm must be freed before this_arg is
164 #[no_mangle]
165 pub extern "C" fn ChainMonitor_as_Confirm(this_arg: &ChainMonitor) -> crate::lightning::chain::Confirm {
166         crate::lightning::chain::Confirm {
167                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
168                 free: None,
169                 transactions_confirmed: ChainMonitor_Confirm_transactions_confirmed,
170                 transaction_unconfirmed: ChainMonitor_Confirm_transaction_unconfirmed,
171                 best_block_updated: ChainMonitor_Confirm_best_block_updated,
172                 get_relevant_txids: ChainMonitor_Confirm_get_relevant_txids,
173         }
174 }
175
176 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) {
177         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 }); };
178         <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)
179 }
180 extern "C" fn ChainMonitor_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) {
181         <nativeChainMonitor as lightning::chain::Confirm<>>::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
182 }
183 extern "C" fn ChainMonitor_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
184         <nativeChainMonitor as lightning::chain::Confirm<>>::best_block_updated(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
185 }
186 #[must_use]
187 extern "C" fn ChainMonitor_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ {
188         let mut ret = <nativeChainMonitor as lightning::chain::Confirm<>>::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
189         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
190         local_ret.into()
191 }
192
193 impl From<nativeChainMonitor> for crate::lightning::chain::Watch {
194         fn from(obj: nativeChainMonitor) -> Self {
195                 let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
196                 let mut ret = ChainMonitor_as_Watch(&rust_obj);
197                 // 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
198                 rust_obj.inner = std::ptr::null_mut();
199                 ret.free = Some(ChainMonitor_free_void);
200                 ret
201         }
202 }
203 /// Constructs a new Watch which calls the relevant methods on this_arg.
204 /// This copies the `inner` pointer in this_arg and thus the returned Watch must be freed before this_arg is
205 #[no_mangle]
206 pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::lightning::chain::Watch {
207         crate::lightning::chain::Watch {
208                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
209                 free: None,
210                 watch_channel: ChainMonitor_Watch_watch_channel,
211                 update_channel: ChainMonitor_Watch_update_channel,
212                 release_pending_monitor_events: ChainMonitor_Watch_release_pending_monitor_events,
213         }
214 }
215
216 #[must_use]
217 extern "C" fn ChainMonitor_Watch_watch_channel(this_arg: *const c_void, mut funding_outpoint: crate::lightning::chain::transaction::OutPoint, mut monitor: crate::lightning::chain::channelmonitor::ChannelMonitor) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ {
218         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::watch_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_outpoint.take_inner()) }, *unsafe { Box::from_raw(monitor.take_inner()) });
219         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
220         local_ret
221 }
222 #[must_use]
223 extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, mut update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::c_types::derived::CResult_NoneChannelMonitorUpdateErrZ {
224         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()) }, *unsafe { Box::from_raw(update.take_inner()) });
225         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
226         local_ret
227 }
228 #[must_use]
229 extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ {
230         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::release_pending_monitor_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
231         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
232         local_ret.into()
233 }
234
235 impl From<nativeChainMonitor> for crate::lightning::util::events::EventsProvider {
236         fn from(obj: nativeChainMonitor) -> Self {
237                 let mut rust_obj = ChainMonitor { inner: ObjOps::heap_alloc(obj), is_owned: true };
238                 let mut ret = ChainMonitor_as_EventsProvider(&rust_obj);
239                 // 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
240                 rust_obj.inner = std::ptr::null_mut();
241                 ret.free = Some(ChainMonitor_free_void);
242                 ret
243         }
244 }
245 /// Constructs a new EventsProvider which calls the relevant methods on this_arg.
246 /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
247 #[no_mangle]
248 pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::lightning::util::events::EventsProvider {
249         crate::lightning::util::events::EventsProvider {
250                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
251                 free: None,
252                 process_pending_events: ChainMonitor_EventsProvider_process_pending_events,
253         }
254 }
255
256 extern "C" fn ChainMonitor_EventsProvider_process_pending_events(this_arg: *const c_void, mut handler: crate::lightning::util::events::EventHandler) {
257         <nativeChainMonitor as lightning::util::events::EventsProvider<>>::process_pending_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, handler)
258 }
259