Merge pull request #18 from TheBlueMatt/2021-04-invoice-incl
[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(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 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
75 impl ChainMonitor {
76         pub(crate) fn take_inner(mut self) -> *mut nativeChainMonitor {
77                 assert!(self.is_owned);
78                 let ret = self.inner;
79                 self.inner = std::ptr::null_mut();
80                 ret
81         }
82 }
83 /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
84 ///
85 /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
86 /// will call back to it indicating transactions and outputs of interest. This allows clients to
87 /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
88 /// always need to fetch full blocks absent another means for determining which blocks contain
89 /// transactions relevant to the watched channels.
90 #[must_use]
91 #[no_mangle]
92 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 {
93         let mut local_chain_source = if chain_source == std::ptr::null_mut() { None } else { Some( { unsafe { *Box::from_raw(chain_source) } }) };
94         let mut ret = lightning::chain::chainmonitor::ChainMonitor::new(local_chain_source, broadcaster, logger, feeest, persister);
95         ChainMonitor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
96 }
97
98 impl From<nativeChainMonitor> for crate::lightning::chain::Listen {
99         fn from(obj: nativeChainMonitor) -> Self {
100                 let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
101                 let mut ret = ChainMonitor_as_Listen(&rust_obj);
102                 // 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
103                 rust_obj.inner = std::ptr::null_mut();
104                 ret.free = Some(ChainMonitor_free_void);
105                 ret
106         }
107 }
108 /// Constructs a new Listen which calls the relevant methods on this_arg.
109 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
110 #[no_mangle]
111 pub extern "C" fn ChainMonitor_as_Listen(this_arg: &ChainMonitor) -> crate::lightning::chain::Listen {
112         crate::lightning::chain::Listen {
113                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
114                 free: None,
115                 block_connected: ChainMonitor_Listen_block_connected,
116                 block_disconnected: ChainMonitor_Listen_block_disconnected,
117         }
118 }
119
120 extern "C" fn ChainMonitor_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
121         <nativeChainMonitor as lightning::chain::Listen<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
122 }
123 extern "C" fn ChainMonitor_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
124         <nativeChainMonitor as lightning::chain::Listen<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
125 }
126
127 impl From<nativeChainMonitor> for crate::lightning::chain::Confirm {
128         fn from(obj: nativeChainMonitor) -> Self {
129                 let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
130                 let mut ret = ChainMonitor_as_Confirm(&rust_obj);
131                 // 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
132                 rust_obj.inner = std::ptr::null_mut();
133                 ret.free = Some(ChainMonitor_free_void);
134                 ret
135         }
136 }
137 /// Constructs a new Confirm which calls the relevant methods on this_arg.
138 /// This copies the `inner` pointer in this_arg and thus the returned Confirm must be freed before this_arg is
139 #[no_mangle]
140 pub extern "C" fn ChainMonitor_as_Confirm(this_arg: &ChainMonitor) -> crate::lightning::chain::Confirm {
141         crate::lightning::chain::Confirm {
142                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
143                 free: None,
144                 transactions_confirmed: ChainMonitor_Confirm_transactions_confirmed,
145                 transaction_unconfirmed: ChainMonitor_Confirm_transaction_unconfirmed,
146                 best_block_updated: ChainMonitor_Confirm_best_block_updated,
147                 get_relevant_txids: ChainMonitor_Confirm_get_relevant_txids,
148         }
149 }
150
151 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) {
152         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 }); };
153         <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)
154 }
155 extern "C" fn ChainMonitor_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) {
156         <nativeChainMonitor as lightning::chain::Confirm<>>::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
157 }
158 extern "C" fn ChainMonitor_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
159         <nativeChainMonitor as lightning::chain::Confirm<>>::best_block_updated(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
160 }
161 #[must_use]
162 extern "C" fn ChainMonitor_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_TxidZ {
163         let mut ret = <nativeChainMonitor as lightning::chain::Confirm<>>::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
164         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
165         local_ret.into()
166 }
167
168 impl From<nativeChainMonitor> for crate::lightning::chain::Watch {
169         fn from(obj: nativeChainMonitor) -> Self {
170                 let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
171                 let mut ret = ChainMonitor_as_Watch(&rust_obj);
172                 // 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
173                 rust_obj.inner = std::ptr::null_mut();
174                 ret.free = Some(ChainMonitor_free_void);
175                 ret
176         }
177 }
178 /// Constructs a new Watch which calls the relevant methods on this_arg.
179 /// This copies the `inner` pointer in this_arg and thus the returned Watch must be freed before this_arg is
180 #[no_mangle]
181 pub extern "C" fn ChainMonitor_as_Watch(this_arg: &ChainMonitor) -> crate::lightning::chain::Watch {
182         crate::lightning::chain::Watch {
183                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
184                 free: None,
185                 watch_channel: ChainMonitor_Watch_watch_channel,
186                 update_channel: ChainMonitor_Watch_update_channel,
187                 release_pending_monitor_events: ChainMonitor_Watch_release_pending_monitor_events,
188         }
189 }
190
191 #[must_use]
192 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 {
193         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()) });
194         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
195         local_ret
196 }
197 #[must_use]
198 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 {
199         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()) });
200         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::chain::channelmonitor::ChannelMonitorUpdateErr::native_into(e) }).into() };
201         local_ret
202 }
203 #[must_use]
204 extern "C" fn ChainMonitor_Watch_release_pending_monitor_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MonitorEventZ {
205         let mut ret = <nativeChainMonitor as lightning::chain::Watch<_>>::release_pending_monitor_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
206         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::chain::channelmonitor::MonitorEvent::native_into(item) }); };
207         local_ret.into()
208 }
209
210 impl From<nativeChainMonitor> for crate::lightning::util::events::EventsProvider {
211         fn from(obj: nativeChainMonitor) -> Self {
212                 let mut rust_obj = ChainMonitor { inner: Box::into_raw(Box::new(obj)), is_owned: true };
213                 let mut ret = ChainMonitor_as_EventsProvider(&rust_obj);
214                 // 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
215                 rust_obj.inner = std::ptr::null_mut();
216                 ret.free = Some(ChainMonitor_free_void);
217                 ret
218         }
219 }
220 /// Constructs a new EventsProvider which calls the relevant methods on this_arg.
221 /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
222 #[no_mangle]
223 pub extern "C" fn ChainMonitor_as_EventsProvider(this_arg: &ChainMonitor) -> crate::lightning::util::events::EventsProvider {
224         crate::lightning::util::events::EventsProvider {
225                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
226                 free: None,
227                 get_and_clear_pending_events: ChainMonitor_EventsProvider_get_and_clear_pending_events,
228         }
229 }
230
231 #[must_use]
232 extern "C" fn ChainMonitor_EventsProvider_get_and_clear_pending_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_EventZ {
233         let mut ret = <nativeChainMonitor as lightning::util::events::EventsProvider<>>::get_and_clear_pending_events(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, );
234         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::util::events::Event::native_into(item) }); };
235         local_ret.into()
236 }
237