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 alloc::str::FromStr;
14 use core::ffi::c_void;
15 use core::convert::Infallible;
16 use bitcoin::hashes::Hash;
17 use crate::c_types::*;
18 #[cfg(feature="no-std")]
19 use alloc::{vec::Vec, boxed::Box};
20
21
22 use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport;
23 pub(crate) type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
24
25 /// `BackgroundProcessor` takes care of tasks that (1) need to happen periodically to keep
26 /// Rust-Lightning running properly, and (2) either can or should be run in the background. Its
27 /// responsibilities are:
28 /// * Processing [`Event`]s with a user-provided [`EventHandler`].
29 /// * Monitoring whether the [`ChannelManager`] needs to be re-persisted to disk, and if so,
30 ///   writing it to disk/backups by invoking the callback given to it at startup.
31 ///   [`ChannelManager`] persistence should be done in the background.
32 /// * Calling [`ChannelManager::timer_tick_occurred`] and [`PeerManager::timer_tick_occurred`]
33 ///   at the appropriate intervals.
34 /// * Calling [`NetworkGraph::remove_stale_channels`] (if a [`GossipSync`] with a [`NetworkGraph`]
35 ///   is provided to [`BackgroundProcessor::start`]).
36 ///
37 /// It will also call [`PeerManager::process_events`] periodically though this shouldn't be relied
38 /// upon as doing so may result in high latency.
39 ///
40 /// # Note
41 ///
42 /// If [`ChannelManager`] persistence fails and the persisted manager becomes out-of-date, then
43 /// there is a risk of channels force-closing on startup when the manager realizes it's outdated.
44 /// However, as long as [`ChannelMonitor`] backups are sound, no funds besides those used for
45 /// unilateral chain closure fees are at risk.
46 ///
47 /// [`ChannelMonitor`]: lightning::chain::channelmonitor::ChannelMonitor
48 /// [`Event`]: lightning::util::events::Event
49 ///BackgroundProcessor will immediately stop on drop. It should be stored until shutdown.
50 #[must_use]
51 #[repr(C)]
52 pub struct BackgroundProcessor {
53         /// A pointer to the opaque Rust object.
54
55         /// Nearly everywhere, inner must be non-null, however in places where
56         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
57         pub inner: *mut nativeBackgroundProcessor,
58         /// Indicates that this is the only struct which contains the same pointer.
59
60         /// Rust functions which take ownership of an object provided via an argument require
61         /// this to be true and invalidate the object pointed to by inner.
62         pub is_owned: bool,
63 }
64
65 impl Drop for BackgroundProcessor {
66         fn drop(&mut self) {
67                 if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) {
68                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
69                 }
70         }
71 }
72 /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL.
73 #[no_mangle]
74 pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { }
75 #[allow(unused)]
76 /// Used only if an object of this type is returned as a trait impl by a method
77 pub(crate) extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) {
78         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBackgroundProcessor); }
79 }
80 #[allow(unused)]
81 impl BackgroundProcessor {
82         pub(crate) fn get_native_ref(&self) -> &'static nativeBackgroundProcessor {
83                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
84         }
85         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBackgroundProcessor {
86                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
87         }
88         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
89         pub(crate) fn take_inner(mut self) -> *mut nativeBackgroundProcessor {
90                 assert!(self.is_owned);
91                 let ret = ObjOps::untweak_ptr(self.inner);
92                 self.inner = core::ptr::null_mut();
93                 ret
94         }
95 }
96 /// Either [`P2PGossipSync`] or [`RapidGossipSync`].
97 #[must_use]
98 #[repr(C)]
99 pub enum GossipSync {
100         /// Gossip sync via the lightning peer-to-peer network as defined by BOLT 7.
101         P2P(crate::lightning::routing::gossip::P2PGossipSync),
102         /// Rapid gossip sync from a trusted server.
103         Rapid(crate::lightning_rapid_gossip_sync::RapidGossipSync),
104         /// No gossip sync.
105         None,
106 }
107 use lightning_background_processor::GossipSync as GossipSyncImport;
108 pub(crate) type nativeGossipSync = GossipSyncImport<&'static lightning::routing::gossip::P2PGossipSync<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::chain::Access, crate::lightning::util::logger::Logger>, &'static lightning_rapid_gossip_sync::RapidGossipSync<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>, &'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::chain::Access, crate::lightning::util::logger::Logger>;
109
110 impl GossipSync {
111         #[allow(unused)]
112         pub(crate) fn into_native(self) -> nativeGossipSync {
113                 match self {
114                         GossipSync::P2P (mut a, ) => {
115                                 nativeGossipSync::P2P (
116                                         a.get_native_ref(),
117                                 )
118                         },
119                         GossipSync::Rapid (mut a, ) => {
120                                 nativeGossipSync::Rapid (
121                                         a.get_native_ref(),
122                                 )
123                         },
124                         GossipSync::None => nativeGossipSync::None,
125                 }
126         }
127         #[allow(unused)]
128         pub(crate) fn native_into(native: nativeGossipSync) -> Self {
129                 match native {
130                         nativeGossipSync::P2P (mut a, ) => {
131                                 GossipSync::P2P (
132                                         crate::lightning::routing::gossip::P2PGossipSync { inner: unsafe { ObjOps::nonnull_ptr_to_inner((a as *const lightning::routing::gossip::P2PGossipSync<_, _, _, >) as *mut _) }, is_owned: false },
133                                 )
134                         },
135                         nativeGossipSync::Rapid (mut a, ) => {
136                                 GossipSync::Rapid (
137                                         crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: unsafe { ObjOps::nonnull_ptr_to_inner((a as *const lightning_rapid_gossip_sync::RapidGossipSync<_, _, >) as *mut _) }, is_owned: false },
138                                 )
139                         },
140                         nativeGossipSync::None => GossipSync::None,
141                 }
142         }
143 }
144 /// Frees any resources used by the GossipSync
145 #[no_mangle]
146 pub extern "C" fn GossipSync_free(this_ptr: GossipSync) { }
147 #[no_mangle]
148 /// Utility method to constructs a new P2P-variant GossipSync
149 pub extern "C" fn GossipSync_p2_p(a: crate::lightning::routing::gossip::P2PGossipSync) -> GossipSync {
150         GossipSync::P2P(a, )
151 }
152 #[no_mangle]
153 /// Utility method to constructs a new Rapid-variant GossipSync
154 pub extern "C" fn GossipSync_rapid(a: crate::lightning_rapid_gossip_sync::RapidGossipSync) -> GossipSync {
155         GossipSync::Rapid(a, )
156 }
157 #[no_mangle]
158 /// Utility method to constructs a new None-variant GossipSync
159 pub extern "C" fn GossipSync_none() -> GossipSync {
160         GossipSync::None}
161 /// Start a background thread that takes care of responsibilities enumerated in the [top-level
162 /// documentation].
163 ///
164 /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
165 /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling
166 /// either [`join`] or [`stop`].
167 ///
168 /// # Data Persistence
169 ///
170 /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or
171 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
172 /// [`ChannelManager`]. See the `lightning-persister` crate for LDK's
173 /// provided implementation.
174 ///
175 /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk, if
176 /// [`GossipSync`] is supplied. See [`NetworkGraph::write`] for writing out a [`NetworkGraph`].
177 /// See the `lightning-persister` crate for LDK's provided implementation.
178 ///
179 /// Typically, users should either implement [`Persister::persist_manager`] to never return an
180 /// error or call [`join`] and handle any error that may arise. For the latter case,
181 /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
182 ///
183 /// # Event Handling
184 ///
185 /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
186 /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
187 /// functionality implemented by other handlers.
188 /// * [`P2PGossipSync`] if given will update the [`NetworkGraph`] based on payment failures.
189 ///
190 /// # Rapid Gossip Sync
191 ///
192 /// If rapid gossip sync is meant to run at startup, pass a [`RapidGossipSync`] to `gossip_sync`
193 /// to indicate that the [`BackgroundProcessor`] should not prune the [`NetworkGraph`] instance
194 /// until the [`RapidGossipSync`] instance completes its first sync.
195 ///
196 /// [top-level documentation]: BackgroundProcessor
197 /// [`join`]: Self::join
198 /// [`stop`]: Self::stop
199 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
200 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
201 /// [`Persister::persist_manager`]: lightning::util::persist::Persister::persist_manager
202 /// [`Persister::persist_graph`]: lightning::util::persist::Persister::persist_graph
203 /// [`NetworkGraph`]: lightning::routing::gossip::NetworkGraph
204 /// [`NetworkGraph::write`]: lightning::routing::gossip::NetworkGraph#impl-Writeable
205 #[must_use]
206 #[no_mangle]
207 pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning::util::persist::Persister, mut event_handler: crate::lightning::util::events::EventHandler, chain_monitor: &crate::lightning::chain::chainmonitor::ChainMonitor, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager, mut gossip_sync: crate::lightning_background_processor::GossipSync, peer_manager: &crate::lightning::ln::peer_handler::PeerManager, mut logger: crate::lightning::util::logger::Logger, mut scorer: crate::c_types::derived::COption_WriteableScoreZ) -> crate::lightning_background_processor::BackgroundProcessor {
208         let mut local_scorer = { /* scorer*/ let scorer_opt = scorer; { } if scorer_opt.is_none() { None } else { Some({ scorer_opt.take() }) } };
209         let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, chain_monitor.get_native_ref(), channel_manager.get_native_ref(), gossip_sync.into_native(), peer_manager.get_native_ref(), logger, local_scorer);
210         crate::lightning_background_processor::BackgroundProcessor { inner: ObjOps::heap_alloc(ret), is_owned: true }
211 }
212
213 /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
214 /// [`ChannelManager`].
215 ///
216 /// # Panics
217 ///
218 /// This function panics if the background thread has panicked such as while persisting or
219 /// handling events.
220 ///
221 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
222 #[must_use]
223 #[no_mangle]
224 pub extern "C" fn BackgroundProcessor_join(mut this_arg: crate::lightning_background_processor::BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
225         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join();
226         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() };
227         local_ret
228 }
229
230 /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
231 /// [`ChannelManager`].
232 ///
233 /// # Panics
234 ///
235 /// This function panics if the background thread has panicked such as while persisting or
236 /// handling events.
237 ///
238 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
239 #[must_use]
240 #[no_mangle]
241 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: crate::lightning_background_processor::BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
242         let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop();
243         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() };
244         local_ret
245 }
246