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