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