Update auto-generated bindings
[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 bitcoin::hashes::Hash;
16 use crate::c_types::*;
17
18
19 use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport;
20 type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
21
22 /// BackgroundProcessor takes care of tasks that (1) need to happen periodically to keep
23 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
24 /// responsibilities are:
25 /// * Monitoring whether the ChannelManager needs to be re-persisted to disk, and if so,
26 ///   writing it to disk/backups by invoking the callback given to it at startup.
27 ///   ChannelManager persistence should be done in the background.
28 /// * Calling `ChannelManager::timer_tick_occurred()` and
29 ///   `PeerManager::timer_tick_occurred()` every minute (can be done in the
30 ///   background).
31 ///
32 /// Note that if ChannelManager persistence fails and the persisted manager becomes out-of-date,
33 /// then there is a risk of channels force-closing on startup when the manager realizes it's
34 /// outdated. However, as long as `ChannelMonitor` backups are sound, no funds besides those used
35 /// for unilateral chain closure fees are at risk.
36 ///BackgroundProcessor will immediately stop on drop. It should be stored until shutdown.
37 #[must_use]
38 #[repr(C)]
39 pub struct BackgroundProcessor {
40         /// A pointer to the opaque Rust object.
41
42         /// Nearly everywhere, inner must be non-null, however in places where
43         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
44         pub inner: *mut nativeBackgroundProcessor,
45         /// Indicates that this is the only struct which contains the same pointer.
46
47         /// Rust functions which take ownership of an object provided via an argument require
48         /// this to be true and invalidate the object pointed to by inner.
49         pub is_owned: bool,
50 }
51
52 impl Drop for BackgroundProcessor {
53         fn drop(&mut self) {
54                 if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) {
55                         let _ = unsafe { Box::from_raw(self.inner) };
56                 }
57         }
58 }
59 /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL.
60 #[no_mangle]
61 pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { }
62 #[allow(unused)]
63 /// Used only if an object of this type is returned as a trait impl by a method
64 extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) {
65         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBackgroundProcessor); }
66 }
67 #[allow(unused)]
68 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
69 impl BackgroundProcessor {
70         pub(crate) fn take_inner(mut self) -> *mut nativeBackgroundProcessor {
71                 assert!(self.is_owned);
72                 let ret = self.inner;
73                 self.inner = std::ptr::null_mut();
74                 ret
75         }
76 }
77 /// Trait which handles persisting a [`ChannelManager`] to disk.
78 ///
79 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
80 #[repr(C)]
81 pub struct ChannelManagerPersister {
82         /// An opaque pointer which is passed to your function implementations as an argument.
83         /// This has no meaning in the LDK, and can be NULL or any other value.
84         pub this_arg: *mut c_void,
85         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
86         /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
87         ///
88         /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
89         #[must_use]
90         pub persist_manager: extern "C" fn (this_arg: *const c_void, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ,
91         /// Frees any resources associated with this object given its this_arg pointer.
92         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
93         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
94 }
95 unsafe impl Send for ChannelManagerPersister {}
96 unsafe impl Sync for ChannelManagerPersister {}
97 #[no_mangle]
98 pub(crate) extern "C" fn ChannelManagerPersister_clone_fields(orig: &ChannelManagerPersister) -> ChannelManagerPersister {
99         ChannelManagerPersister {
100                 this_arg: orig.this_arg,
101                 persist_manager: Clone::clone(&orig.persist_manager),
102                 free: Clone::clone(&orig.free),
103         }
104 }
105
106 use lightning_background_processor::ChannelManagerPersister as rustChannelManagerPersister;
107 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 {
108         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> {
109                 let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { (channel_manager as *const _) as *mut _ }, is_owned: false });
110                 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() })};
111                 local_ret
112         }
113 }
114
115 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
116 // directly as a Deref trait in higher-level structs:
117 impl std::ops::Deref for ChannelManagerPersister {
118         type Target = Self;
119         fn deref(&self) -> &Self {
120                 self
121         }
122 }
123 /// Calls the free function if one is set
124 #[no_mangle]
125 pub extern "C" fn ChannelManagerPersister_free(this_ptr: ChannelManagerPersister) { }
126 impl Drop for ChannelManagerPersister {
127         fn drop(&mut self) {
128                 if let Some(f) = self.free {
129                         f(self.this_arg);
130                 }
131         }
132 }
133 /// Start a background thread that takes care of responsibilities enumerated in the [top-level
134 /// documentation].
135 ///
136 /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
137 /// `persist_manager` returns an error. In case of an error, the error is retrieved by calling
138 /// either [`join`] or [`stop`].
139 ///
140 /// Typically, users should either implement [`ChannelManagerPersister`] to never return an
141 /// error or call [`join`] and handle any error that may arise. For the latter case, the
142 /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
143 ///
144 /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
145 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
146 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
147 /// provided implementation.
148 ///
149 /// [top-level documentation]: Self
150 /// [`join`]: Self::join
151 /// [`stop`]: Self::stop
152 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
153 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
154 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
155 #[must_use]
156 #[no_mangle]
157 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, peer_manager: &crate::lightning::ln::peer_handler::PeerManager, mut logger: crate::lightning::util::logger::Logger) -> BackgroundProcessor {
158         let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, unsafe { &*chain_monitor.inner }, unsafe { &*channel_manager.inner }, unsafe { &*peer_manager.inner }, logger);
159         BackgroundProcessor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
160 }
161
162 /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
163 /// [`ChannelManager`].
164 ///
165 /// # Panics
166 ///
167 /// This function panics if the background thread has panicked such as while persisting or
168 /// handling events.
169 ///
170 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
171 #[must_use]
172 #[no_mangle]
173 pub extern "C" fn BackgroundProcessor_join(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
174         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join();
175         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() };
176         local_ret
177 }
178
179 /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
180 /// [`ChannelManager`].
181 ///
182 /// # Panics
183 ///
184 /// This function panics if the background thread has panicked such as while persisting or
185 /// handling events.
186 ///
187 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
188 #[must_use]
189 #[no_mangle]
190 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
191         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop();
192         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() };
193         local_ret
194 }
195