Merge pull request #51 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / lightning_background_processor.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 //! Utilities that take care of tasks that (1) need to happen periodically to keep Rust-Lightning
10 //! running properly, and (2) either can or should be run in the background. See docs for
11 //! [`BackgroundProcessor`] for more details on the nitty-gritty.
12
13 use std::str::FromStr;
14 use std::ffi::c_void;
15 use core::convert::Infallible;
16 use bitcoin::hashes::Hash;
17 use crate::c_types::*;
18
19
20 use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport;
21 pub(crate) type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
22
23 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
24 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
25 /// responsibilities are:
26 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
27 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
28 ///   writing it to disk/backups by invoking the callback given to it at startup.
29 ///   [`ChannelManager`] persistence should be done in the background.
30 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
31 ///   at the appropriate intervals.
32 /// * Calling [`NetworkGraph::remove_stale_channels`] (if a [`NetGraphMsgHandler`] is provided to
33 ///   [`BackgroundProcessor::start`]).
34 ///
35 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
36 /// upon as doing so may result in high latency.
37 ///
38 /// # Note
39 ///
40 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
41 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
42 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
43 /// unilateral chain closure fees are at risk.
44 ///
45 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
46 /// [`Event`]: lightning::util::events::Event
47 ///BackgroundProcessor will immediately stop on drop. It should be stored until shutdown.
48 #[must_use]
49 #[repr(C)]
50 pub struct BackgroundProcessor {
51         /// A pointer to the opaque Rust object.
52
53         /// Nearly everywhere, inner must be non-null, however in places where
54         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
55         pub inner: *mut nativeBackgroundProcessor,
56         /// Indicates that this is the only struct which contains the same pointer.
57
58         /// Rust functions which take ownership of an object provided via an argument require
59         /// this to be true and invalidate the object pointed to by inner.
60         pub is_owned: bool,
61 }
62
63 impl Drop for BackgroundProcessor {
64         fn drop(&mut self) {
65                 if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) {
66                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
67                 }
68         }
69 }
70 /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL.
71 #[no_mangle]
72 pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { }
73 #[allow(unused)]
74 /// Used only if an object of this type is returned as a trait impl by a method
75 pub(crate) extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) {
76         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBackgroundProcessor); }
77 }
78 #[allow(unused)]
79 impl BackgroundProcessor {
80         pub(crate) fn get_native_ref(&self) -> &'static nativeBackgroundProcessor {
81                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
82         }
83         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBackgroundProcessor {
84                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
85         }
86         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
87         pub(crate) fn take_inner(mut self) -> *mut nativeBackgroundProcessor {
88                 assert!(self.is_owned);
89                 let ret = ObjOps::untweak_ptr(self.inner);
90                 self.inner = std::ptr::null_mut();
91                 ret
92         }
93 }
94 /// Trait which handles persisting a [`ChannelManager`] to disk.
95 ///
96 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
97 #[repr(C)]
98 pub struct ChannelManagerPersister {
99         /// An opaque pointer which is passed to your function implementations as an argument.
100         /// This has no meaning in the LDK, and can be NULL or any other value.
101         pub this_arg: *mut c_void,
102         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
103         /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
104         ///
105         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
106         #[must_use]
107         pub persist_manager: extern "C" fn (this_arg: *const c_void, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ,
108         /// Frees any resources associated with this object given its this_arg pointer.
109         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
110         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
111 }
112 unsafe impl Send for ChannelManagerPersister {}
113 unsafe impl Sync for ChannelManagerPersister {}
114 #[no_mangle]
115 pub(crate) extern "C" fn ChannelManagerPersister_clone_fields(orig: &ChannelManagerPersister) -> ChannelManagerPersister {
116         ChannelManagerPersister {
117                 this_arg: orig.this_arg,
118                 persist_manager: Clone::clone(&orig.persist_manager),
119                 free: Clone::clone(&orig.free),
120         }
121 }
122
123 use lightning_background_processor::ChannelManagerPersister as rustChannelManagerPersister;
124 impl rustChannelManagerPersister<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger> for ChannelManagerPersister {
125         fn persist_manager(&self, mut channel_manager: &lightning::ln::channelmanager::ChannelManager<crate::lightning::chain::keysinterface::Sign, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger>) -> Result<(), std::io::Error> {
126                 let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_manager as *const lightning::ln::channelmanager::ChannelManager<_, _, _, _, _, _, >) as *mut _) }, is_owned: false });
127                 let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).to_rust() })};
128                 local_ret
129         }
130 }
131
132 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
133 // directly as a Deref trait in higher-level structs:
134 impl std::ops::Deref for ChannelManagerPersister {
135         type Target = Self;
136         fn deref(&self) -> &Self {
137                 self
138         }
139 }
140 /// Calls the free function if one is set
141 #[no_mangle]
142 pub extern "C" fn ChannelManagerPersister_free(this_ptr: ChannelManagerPersister) { }
143 impl Drop for ChannelManagerPersister {
144         fn drop(&mut self) {
145                 if let Some(f) = self.free {
146                         f(self.this_arg);
147                 }
148         }
149 }
150 /// Start a background thread that takes care of responsibilities enumerated in the [top-level
151 /// documentation].
152 ///
153 /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
154 /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
155 /// either [`join`] or [`stop`].
156 ///
157 /// # Data Persistence
158 ///
159 /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
160 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
161 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
162 /// provided implementation.
163 ///
164 /// Typically, users should either implement [`ChannelManagerPersister`] to never return an
165 /// error or call [`join`] and handle any error that may arise. For the latter case,
166 /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
167 ///
168 /// # Event Handling
169 ///
170 /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
171 /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
172 /// functionality implemented by other handlers.
173 /// * [`NetGraphMsgHandler`] if given will update the [`NetworkGraph`] based on payment failures.
174 ///
175 /// [top-level documentation]: BackgroundProcessor
176 /// [`join`]: Self::join
177 /// [`stop`]: Self::stop
178 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
179 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
180 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
181 /// [`NetworkGraph`]: lightning::routing::network_graph::NetworkGraph
182 ///
183 /// Note that net_graph_msg_handler (or a relevant inner pointer) may be NULL or all-0s to represent None
184 #[must_use]
185 #[no_mangle]
186 pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning_background_processor::ChannelManagerPersister, mut event_handler: crate::lightning::util::events::EventHandler, chain_monitor: &crate::lightning::chain::chainmonitor::ChainMonitor, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager, mut net_graph_msg_handler: crate::lightning::routing::network_graph::NetGraphMsgHandler, peer_manager: &crate::lightning::ln::peer_handler::PeerManager, mut logger: crate::lightning::util::logger::Logger) -> BackgroundProcessor {
187         let mut local_net_graph_msg_handler = if net_graph_msg_handler.inner.is_null() { None } else { Some( { net_graph_msg_handler.get_native_ref() }) };
188         let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, chain_monitor.get_native_ref(), channel_manager.get_native_ref(), local_net_graph_msg_handler, peer_manager.get_native_ref(), logger);
189         BackgroundProcessor { inner: ObjOps::heap_alloc(ret), is_owned: true }
190 }
191
192 /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
193 /// [`ChannelManager`].
194 ///
195 /// # Panics
196 ///
197 /// This function panics if the background thread has panicked such as while persisting or
198 /// handling events.
199 ///
200 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
201 #[must_use]
202 #[no_mangle]
203 pub extern "C" fn BackgroundProcessor_join(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
204         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join();
205         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::c_types::IOError::from_rust(e) }).into() };
206         local_ret
207 }
208
209 /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
210 /// [`ChannelManager`].
211 ///
212 /// # Panics
213 ///
214 /// This function panics if the background thread has panicked such as while persisting or
215 /// handling events.
216 ///
217 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
218 #[must_use]
219 #[no_mangle]
220 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
221         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop();
222         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::c_types::IOError::from_rust(e) }).into() };
223         local_ret
224 }
225