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 std::str::FromStr;
15 use bitcoin::hashes::Hash;
16 use crate::c_types::*;
19 use lightning_background_processor::BackgroundProcessor as nativeBackgroundProcessorImport;
20 type nativeBackgroundProcessor = nativeBackgroundProcessorImport;
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
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.
38 pub struct BackgroundProcessor {
39 /// A pointer to the opaque Rust object.
41 /// Nearly everywhere, inner must be non-null, however in places where
42 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
43 pub inner: *mut nativeBackgroundProcessor,
44 /// Indicates that this is the only struct which contains the same pointer.
46 /// Rust functions which take ownership of an object provided via an argument require
47 /// this to be true and invalidate the object pointed to by inner.
51 impl Drop for BackgroundProcessor {
53 if self.is_owned && !<*mut nativeBackgroundProcessor>::is_null(self.inner) {
54 let _ = unsafe { Box::from_raw(self.inner) };
58 /// Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL.
60 pub extern "C" fn BackgroundProcessor_free(this_obj: BackgroundProcessor) { }
62 /// Used only if an object of this type is returned as a trait impl by a method
63 extern "C" fn BackgroundProcessor_free_void(this_ptr: *mut c_void) {
64 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBackgroundProcessor); }
67 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
68 impl BackgroundProcessor {
69 pub(crate) fn take_inner(mut self) -> *mut nativeBackgroundProcessor {
70 assert!(self.is_owned);
72 self.inner = std::ptr::null_mut();
76 /// Trait which handles persisting a [`ChannelManager`] to disk.
78 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
80 pub struct ChannelManagerPersister {
81 /// An opaque pointer which is passed to your function implementations as an argument.
82 /// This has no meaning in the LDK, and can be NULL or any other value.
83 pub this_arg: *mut c_void,
84 /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed
85 /// (which will cause the [`BackgroundProcessor`] which called this method to exit.
87 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
89 pub persist_manager: extern "C" fn (this_arg: *const c_void, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneErrorZ,
90 /// Frees any resources associated with this object given its this_arg pointer.
91 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
92 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
94 unsafe impl Send for ChannelManagerPersister {}
95 unsafe impl Sync for ChannelManagerPersister {}
97 use lightning_background_processor::ChannelManagerPersister as rustChannelManagerPersister;
98 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 {
99 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> {
100 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 });
101 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() })};
106 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
107 // directly as a Deref trait in higher-level structs:
108 impl std::ops::Deref for ChannelManagerPersister {
110 fn deref(&self) -> &Self {
114 /// Calls the free function if one is set
116 pub extern "C" fn ChannelManagerPersister_free(this_ptr: ChannelManagerPersister) { }
117 impl Drop for ChannelManagerPersister {
119 if let Some(f) = self.free {
124 /// Start a background thread that takes care of responsibilities enumerated in the top-level
127 /// If `persist_manager` returns an error, then this thread will return said error (and
128 /// `start()` will need to be called again to restart the `BackgroundProcessor`). Users should
129 /// wait on [`thread_handle`]'s `join()` method to be able to tell if and when an error is
130 /// returned, or implement `persist_manager` such that an error is never returned to the
131 /// `BackgroundProcessor`
133 /// `persist_manager` is responsible for writing out the [`ChannelManager`] to disk, and/or
134 /// uploading to one or more backup services. See [`ChannelManager::write`] for writing out a
135 /// [`ChannelManager`]. See [`FilesystemPersister::persist_manager`] for Rust-Lightning's
136 /// provided implementation.
138 /// [`thread_handle`]: BackgroundProcessor::thread_handle
139 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
140 /// [`ChannelManager::write`]: lightning::ln::channelmanager::ChannelManager#impl-Writeable
141 /// [`FilesystemPersister::persist_manager`]: lightning_persister::FilesystemPersister::persist_manager
144 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 {
145 let mut ret = lightning_background_processor::BackgroundProcessor::start(persister, event_handler, unsafe { &*chain_monitor.inner }, unsafe { &*channel_manager.inner }, unsafe { &*peer_manager.inner }, logger);
146 BackgroundProcessor { inner: Box::into_raw(Box::new(ret)), is_owned: true }
149 /// Stop `BackgroundProcessor`'s thread.
152 pub extern "C" fn BackgroundProcessor_stop(mut this_arg: BackgroundProcessor) -> crate::c_types::derived::CResult_NoneErrorZ {
153 let mut ret = (*unsafe { Box::from_raw(this_arg.take_inner()) }).stop();
154 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() };