1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
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.
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.
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};
22 use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport;
23 pub(crate) type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
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 [`NetGraphMsgHandler`] is provided to
35 /// [`BackgroundProcessor::start`]).
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.
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.
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.
52 pub struct BackgroundProcessor {
53 /// A pointer to the opaque Rust object.
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.
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.
65 impl Drop for BackgroundProcessor {
67 if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) {
68 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
72 /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL.
74 pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { }
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); }
81 impl BackgroundProcessor {
82 pub(crate) fn get_native_ref(&self) -> &'static nativeBackgroundProcessor {
83 unsafe { &*ObjOps::untweak_ptr(self.inner) }
85 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBackgroundProcessor {
86 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
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();
96 /// Trait that handles persisting a [`ChannelManager`] and [`NetworkGraph`] to disk.
98 pub struct Persister {
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).
105 pub persist_manager: extern "C" fn (this_arg: *const c_void, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ,
106 /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
108 pub persist_graph: extern "C" fn (this_arg: *const c_void, network_graph: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::c_types::derived::CResult_NoneErrorZ,
109 /// Frees any resources associated with this object given its this_arg pointer.
110 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
111 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
113 unsafe impl Send for Persister {}
114 unsafe impl Sync for Persister {}
116 pub(crate) extern "C" fn Persister_clone_fields(orig: &Persister) -> Persister {
118 this_arg: orig.this_arg,
119 persist_manager: Clone::clone(&orig.persist_manager),
120 persist_graph: Clone::clone(&orig.persist_graph),
121 free: Clone::clone(&orig.free),
125 use lightning_background_processor::Persister as rustPersister;
126 impl rustPersister<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 Persister {
127 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> {
128 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 });
129 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() })};
132 fn persist_graph(&self, mut network_graph: &lightning::routing::network_graph::NetworkGraph) -> Result<(), std::io::Error> {
133 let mut ret = (self.persist_graph)(self.this_arg, &crate::lightning::routing::network_graph::NetworkGraph { inner: unsafe { ObjOps::nonnull_ptr_to_inner((network_graph as *const lightning::routing::network_graph::NetworkGraph<>) as *mut _) }, is_owned: false });
134 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() })};
139 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
140 // directly as a Deref trait in higher-level structs:
141 impl core::ops::Deref for Persister {
143 fn deref(&self) -> &Self {
147 /// Calls the free function if one is set
149 pub extern "C" fn Persister_free(this_ptr: Persister) { }
150 impl Drop for Persister {
152 if let Some(f) = self.free {
157 /// Start a background thread that takes care of responsibilities enumerated in the [top-level
160 /// The thread runs indefinitely unless the object is dropped, [`stop`] is called, or
161 /// [`Persister::persist_manager`] returns an error. In case of an error, the error is retrieved by calling
162 /// either [`join`] or [`stop`].
164 /// # Data Persistence
166 /// [`Persister::persist_manager`] is responsible for writing out the [`ChannelManager`] to disk, and/or
167 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
168 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
169 /// provided implementation.
171 /// [`Persister::persist_graph`] is responsible for writing out the [`NetworkGraph`] to disk. See
172 /// [`NetworkGraph::write`] for writing out a [`NetworkGraph`]. See [`FilesystemPersister::persist_network_graph`]
173 /// for Rust-Lightning's provided implementation.
175 /// Typically, users should either implement [`Persister::persist_manager`] to never return an
176 /// error or call [`join`] and handle any error that may arise. For the latter case,
177 /// `BackgroundProcessor` must be restarted by calling `start` again after handling the error.
181 /// `event_handler` is responsible for handling events that users should be notified of (e.g.,
182 /// payment failed). [`BackgroundProcessor`] may decorate the given [`EventHandler`] with common
183 /// functionality implemented by other handlers.
184 /// * [`NetGraphMsgHandler`] if given will update the [`NetworkGraph`] based on payment failures.
186 /// [top-level documentation]: BackgroundProcessor
187 /// [`join`]: Self::join
188 /// [`stop`]: Self::stop
189 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
190 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
191 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
192 /// [`FilesystemPersister::persist_network_graph`]: lightning_persister::FilesystemPersister::persist_network_graph
193 /// [`NetworkGraph`]: lightning::routing::network_graph::NetworkGraph
194 /// [`NetworkGraph::write`]: lightning::routing::network_graph::NetworkGraph#impl-Writeable
196 /// Note that net_graph_msg_handler (or a relevant inner pointer) may be NULL or all-0s to represent None
199 pub extern "C" fn BackgroundProcessor_start(mut persister: crate::lightning_background_processor::Persister, 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 {
200 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() }) };
201 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);
202 BackgroundProcessor { inner: ObjOps::heap_alloc(ret), is_owned: true }
205 /// Join `BackgroundProcessor`'s thread, returning any error that occurred while persisting
206 /// [`ChannelManager`].
210 /// This function panics if the background thread has panicked such as while persisting or
213 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
216 pub extern "C" fn BackgroundProcessor_join(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
217 let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).join();
218 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() };
222 /// Stop `BackgroundProcessor`'s thread, returning any error that occurred while persisting
223 /// [`ChannelManager`].
227 /// This function panics if the background thread has panicked such as while persisting or
230 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
233 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
234 let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop();
235 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() };