Pin compiler_builtins to 0.1.109 when building std
[ldk-c-bindings] / lightning-c-bindings / src / lightning / util / persist.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 //! This module contains a simple key-value store trait [`KVStore`] that
10 //! allows one to implement the persistence for [`ChannelManager`], [`NetworkGraph`],
11 //! and [`ChannelMonitor`] all in one place.
12 //!
13 //! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
14
15 use alloc::str::FromStr;
16 use alloc::string::String;
17 use core::ffi::c_void;
18 use core::convert::Infallible;
19 use bitcoin::hashes::Hash;
20 use crate::c_types::*;
21 #[cfg(feature="no-std")]
22 use alloc::{vec::Vec, boxed::Box};
23
24 /// The maximum number of characters namespaces and keys may have.
25
26 #[no_mangle]
27 pub static KVSTORE_NAMESPACE_KEY_MAX_LEN: usize = lightning::util::persist::KVSTORE_NAMESPACE_KEY_MAX_LEN;
28 /// Provides an interface that allows storage and retrieval of persisted values that are associated
29 /// with given keys.
30 ///
31 /// In order to avoid collisions the key space is segmented based on the given `primary_namespace`s
32 /// and `secondary_namespace`s. Implementations of this trait are free to handle them in different
33 /// ways, as long as per-namespace key uniqueness is asserted.
34 ///
35 /// Keys and namespaces are required to be valid ASCII strings in the range of
36 /// [`KVSTORE_NAMESPACE_KEY_ALPHABET`] and no longer than [`KVSTORE_NAMESPACE_KEY_MAX_LEN`]. Empty
37 /// primary namespaces and secondary namespaces (`\"\"`) are assumed to be a valid, however, if
38 /// `primary_namespace` is empty, `secondary_namespace` is required to be empty, too. This means
39 /// that concerns should always be separated by primary namespace first, before secondary
40 /// namespaces are used. While the number of primary namespaces will be relatively small and is
41 /// determined at compile time, there may be many secondary namespaces per primary namespace. Note
42 /// that per-namespace uniqueness needs to also hold for keys *and* namespaces in any given
43 /// namespace, i.e., conflicts between keys and equally named
44 /// primary namespaces/secondary namespaces must be avoided.
45 ///
46 /// **Note:** Users migrating custom persistence backends from the pre-v0.0.117 `KVStorePersister`
47 /// interface can use a concatenation of `[{primary_namespace}/[{secondary_namespace}/]]{key}` to
48 /// recover a `key` compatible with the data model previously assumed by `KVStorePersister::persist`.
49 #[repr(C)]
50 pub struct KVStore {
51         /// An opaque pointer which is passed to your function implementations as an argument.
52         /// This has no meaning in the LDK, and can be NULL or any other value.
53         pub this_arg: *mut c_void,
54         /// Returns the data stored for the given `primary_namespace`, `secondary_namespace`, and
55         /// `key`.
56         ///
57         /// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given
58         /// `primary_namespace` and `secondary_namespace`.
59         ///
60         /// [`ErrorKind::NotFound`]: io::ErrorKind::NotFound
61         pub read: extern "C" fn (this_arg: *const c_void, primary_namespace: crate::c_types::Str, secondary_namespace: crate::c_types::Str, key: crate::c_types::Str) -> crate::c_types::derived::CResult_CVec_u8ZIOErrorZ,
62         /// Persists the given data under the given `key`.
63         ///
64         /// Will create the given `primary_namespace` and `secondary_namespace` if not already present
65         /// in the store.
66         pub write: extern "C" fn (this_arg: *const c_void, primary_namespace: crate::c_types::Str, secondary_namespace: crate::c_types::Str, key: crate::c_types::Str, buf: crate::c_types::u8slice) -> crate::c_types::derived::CResult_NoneIOErrorZ,
67         /// Removes any data that had previously been persisted under the given `key`.
68         ///
69         /// If the `lazy` flag is set to `true`, the backend implementation might choose to lazily
70         /// remove the given `key` at some point in time after the method returns, e.g., as part of an
71         /// eventual batch deletion of multiple keys. As a consequence, subsequent calls to
72         /// [`KVStore::list`] might include the removed key until the changes are actually persisted.
73         ///
74         /// Note that while setting the `lazy` flag reduces the I/O burden of multiple subsequent
75         /// `remove` calls, it also influences the atomicity guarantees as lazy `remove`s could
76         /// potentially get lost on crash after the method returns. Therefore, this flag should only be
77         /// set for `remove` operations that can be safely replayed at a later time.
78         ///
79         /// Returns successfully if no data will be stored for the given `primary_namespace`,
80         /// `secondary_namespace`, and `key`, independently of whether it was present before its
81         /// invokation or not.
82         pub remove: extern "C" fn (this_arg: *const c_void, primary_namespace: crate::c_types::Str, secondary_namespace: crate::c_types::Str, key: crate::c_types::Str, lazy: bool) -> crate::c_types::derived::CResult_NoneIOErrorZ,
83         /// Returns a list of keys that are stored under the given `secondary_namespace` in
84         /// `primary_namespace`.
85         ///
86         /// Returns the keys in arbitrary order, so users requiring a particular order need to sort the
87         /// returned keys. Returns an empty list if `primary_namespace` or `secondary_namespace` is unknown.
88         pub list: extern "C" fn (this_arg: *const c_void, primary_namespace: crate::c_types::Str, secondary_namespace: crate::c_types::Str) -> crate::c_types::derived::CResult_CVec_StrZIOErrorZ,
89         /// Frees any resources associated with this object given its this_arg pointer.
90         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
91         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
92 }
93 unsafe impl Send for KVStore {}
94 unsafe impl Sync for KVStore {}
95 #[allow(unused)]
96 pub(crate) fn KVStore_clone_fields(orig: &KVStore) -> KVStore {
97         KVStore {
98                 this_arg: orig.this_arg,
99                 read: Clone::clone(&orig.read),
100                 write: Clone::clone(&orig.write),
101                 remove: Clone::clone(&orig.remove),
102                 list: Clone::clone(&orig.list),
103                 free: Clone::clone(&orig.free),
104         }
105 }
106
107 use lightning::util::persist::KVStore as rustKVStore;
108 impl rustKVStore for KVStore {
109         fn read(&self, mut primary_namespace: &str, mut secondary_namespace: &str, mut key: &str) -> Result<Vec<u8>, lightning::io::Error> {
110                 let mut ret = (self.read)(self.this_arg, primary_namespace.into(), secondary_namespace.into(), key.into());
111                 let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = Vec::new(); for mut item in (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust().drain(..) { local_ret_0.push( { item }); }; local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).to_rust() })};
112                 local_ret
113         }
114         fn write(&self, mut primary_namespace: &str, mut secondary_namespace: &str, mut key: &str, mut buf: &[u8]) -> Result<(), lightning::io::Error> {
115                 let mut local_buf = crate::c_types::u8slice::from_slice(buf);
116                 let mut ret = (self.write)(self.this_arg, primary_namespace.into(), secondary_namespace.into(), key.into(), local_buf);
117                 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() })};
118                 local_ret
119         }
120         fn remove(&self, mut primary_namespace: &str, mut secondary_namespace: &str, mut key: &str, mut lazy: bool) -> Result<(), lightning::io::Error> {
121                 let mut ret = (self.remove)(self.this_arg, primary_namespace.into(), secondary_namespace.into(), key.into(), lazy);
122                 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() })};
123                 local_ret
124         }
125         fn list(&self, mut primary_namespace: &str, mut secondary_namespace: &str) -> Result<Vec<String>, lightning::io::Error> {
126                 let mut ret = (self.list)(self.this_arg, primary_namespace.into(), secondary_namespace.into());
127                 let mut local_ret = match ret.result_ok { true => Ok( { let mut local_ret_0 = Vec::new(); for mut item in (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust().drain(..) { local_ret_0.push( { item.into_string() }); }; local_ret_0 }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).to_rust() })};
128                 local_ret
129         }
130 }
131
132 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
133 // directly as a Deref trait in higher-level structs:
134 impl core::ops::Deref for KVStore {
135         type Target = Self;
136         fn deref(&self) -> &Self {
137                 self
138         }
139 }
140 impl core::ops::DerefMut for KVStore {
141         fn deref_mut(&mut self) -> &mut Self {
142                 self
143         }
144 }
145 /// Calls the free function if one is set
146 #[no_mangle]
147 pub extern "C" fn KVStore_free(this_ptr: KVStore) { }
148 impl Drop for KVStore {
149         fn drop(&mut self) {
150                 if let Some(f) = self.free {
151                         f(self.this_arg);
152                 }
153         }
154 }
155 /// Trait that handles persisting a [`ChannelManager`], [`NetworkGraph`], and [`WriteableScore`] to disk.
156 ///
157 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
158 #[repr(C)]
159 pub struct Persister {
160         /// An opaque pointer which is passed to your function implementations as an argument.
161         /// This has no meaning in the LDK, and can be NULL or any other value.
162         pub this_arg: *mut c_void,
163         /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed.
164         ///
165         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
166         pub persist_manager: extern "C" fn (this_arg: *const c_void, channel_manager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NoneIOErrorZ,
167         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
168         pub persist_graph: extern "C" fn (this_arg: *const c_void, network_graph: &crate::lightning::routing::gossip::NetworkGraph) -> crate::c_types::derived::CResult_NoneIOErrorZ,
169         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
170         pub persist_scorer: extern "C" fn (this_arg: *const c_void, scorer: &crate::lightning::routing::scoring::WriteableScore) -> crate::c_types::derived::CResult_NoneIOErrorZ,
171         /// Frees any resources associated with this object given its this_arg pointer.
172         /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
173         pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
174 }
175 unsafe impl Send for Persister {}
176 unsafe impl Sync for Persister {}
177 #[allow(unused)]
178 pub(crate) fn Persister_clone_fields(orig: &Persister) -> Persister {
179         Persister {
180                 this_arg: orig.this_arg,
181                 persist_manager: Clone::clone(&orig.persist_manager),
182                 persist_graph: Clone::clone(&orig.persist_graph),
183                 persist_scorer: Clone::clone(&orig.persist_scorer),
184                 free: Clone::clone(&orig.free),
185         }
186 }
187
188 use lightning::util::persist::Persister as rustPersister;
189 impl<'a> rustPersister<'a, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger, crate::lightning::routing::scoring::WriteableScore, > for Persister {
190         fn persist_manager(&self, mut channel_manager: &lightning::ln::channelmanager::ChannelManager<crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger>) -> Result<(), lightning::io::Error> {
191                 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 });
192                 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() })};
193                 local_ret
194         }
195         fn persist_graph(&self, mut network_graph: &lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>) -> Result<(), lightning::io::Error> {
196                 let mut ret = (self.persist_graph)(self.this_arg, &crate::lightning::routing::gossip::NetworkGraph { inner: unsafe { ObjOps::nonnull_ptr_to_inner((network_graph as *const lightning::routing::gossip::NetworkGraph<_, >) as *mut _) }, is_owned: false });
197                 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() })};
198                 local_ret
199         }
200         fn persist_scorer(&self, mut scorer: &crate::lightning::routing::scoring::WriteableScore) -> Result<(), lightning::io::Error> {
201                 let mut ret = (self.persist_scorer)(self.this_arg, scorer);
202                 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() })};
203                 local_ret
204         }
205 }
206
207 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
208 // directly as a Deref trait in higher-level structs:
209 impl core::ops::Deref for Persister {
210         type Target = Self;
211         fn deref(&self) -> &Self {
212                 self
213         }
214 }
215 impl core::ops::DerefMut for Persister {
216         fn deref_mut(&mut self) -> &mut Self {
217                 self
218         }
219 }
220 /// Calls the free function if one is set
221 #[no_mangle]
222 pub extern "C" fn Persister_free(this_ptr: Persister) { }
223 impl Drop for Persister {
224         fn drop(&mut self) {
225                 if let Some(f) = self.free {
226                         f(self.this_arg);
227                 }
228         }
229 }
230 /// Read previously persisted [`ChannelMonitor`]s from the store.
231 #[no_mangle]
232 pub extern "C" fn read_channel_monitors(mut kv_store: crate::lightning::util::persist::KVStore, mut entropy_source: crate::lightning::sign::EntropySource, mut signer_provider: crate::lightning::sign::SignerProvider) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesChannelMonitorZZIOErrorZ {
233         let mut ret = lightning::util::persist::read_channel_monitors::<crate::lightning::util::persist::KVStore, crate::lightning::sign::EntropySource, crate::lightning::sign::SignerProvider, >(kv_store, entropy_source, signer_provider);
234         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0_0.as_ref() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_ret_0_0_1), is_owned: true }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() };
235         local_ret
236 }
237
238
239 use lightning::util::persist::MonitorUpdatingPersister as nativeMonitorUpdatingPersisterImport;
240 pub(crate) type nativeMonitorUpdatingPersister = nativeMonitorUpdatingPersisterImport<crate::lightning::util::persist::KVStore, crate::lightning::util::logger::Logger, crate::lightning::sign::EntropySource, crate::lightning::sign::SignerProvider, >;
241
242 /// Implements [`Persist`] in a way that writes and reads both [`ChannelMonitor`]s and
243 /// [`ChannelMonitorUpdate`]s.
244 ///
245 /// # Overview
246 ///
247 /// The main benefit this provides over the [`KVStore`]'s [`Persist`] implementation is decreased
248 /// I/O bandwidth and storage churn, at the expense of more IOPS (including listing, reading, and
249 /// deleting) and complexity. This is because it writes channel monitor differential updates,
250 /// whereas the other (default) implementation rewrites the entire monitor on each update. For
251 /// routing nodes, updates can happen many times per second to a channel, and monitors can be tens
252 /// of megabytes (or more). Updates can be as small as a few hundred bytes.
253 ///
254 /// Note that monitors written with `MonitorUpdatingPersister` are _not_ backward-compatible with
255 /// the default [`KVStore`]'s [`Persist`] implementation. They have a prepended byte sequence,
256 /// [`MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL`], applied to prevent deserialization with other
257 /// persisters. This is because monitors written by this struct _may_ have unapplied updates. In
258 /// order to downgrade, you must ensure that all updates are applied to the monitor, and remove the
259 /// sentinel bytes.
260 ///
261 /// # Storing monitors
262 ///
263 /// Monitors are stored by implementing the [`Persist`] trait, which has two functions:
264 ///
265 ///   - [`Persist::persist_new_channel`], which persists whole [`ChannelMonitor`]s.
266 ///   - [`Persist::update_persisted_channel`], which persists only a [`ChannelMonitorUpdate`]
267 ///
268 /// Whole [`ChannelMonitor`]s are stored in the [`CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE`],
269 /// using the familiar encoding of an [`OutPoint`] (for example, `[SOME-64-CHAR-HEX-STRING]_1`).
270 ///
271 /// Each [`ChannelMonitorUpdate`] is stored in a dynamic secondary namespace, as follows:
272 ///
273 ///   - primary namespace: [`CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE`]
274 ///   - secondary namespace: [the monitor's encoded outpoint name]
275 ///
276 /// Under that secondary namespace, each update is stored with a number string, like `21`, which
277 /// represents its `update_id` value.
278 ///
279 /// For example, consider this channel, named for its transaction ID and index, or [`OutPoint`]:
280 ///
281 ///   - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
282 ///   - Index: `1`
283 ///
284 /// Full channel monitors would be stored at a single key:
285 ///
286 /// `[CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
287 ///
288 /// Updates would be stored as follows (with `/` delimiting primary_namespace/secondary_namespace/key):
289 ///
290 /// ```text
291 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/1
292 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/2
293 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/3
294 /// ```
295 /// ... and so on.
296 ///
297 /// # Reading channel state from storage
298 ///
299 /// Channel state can be reconstructed by calling
300 /// [`MonitorUpdatingPersister::read_all_channel_monitors_with_updates`]. Alternatively, users can
301 /// list channel monitors themselves and load channels individually using
302 /// [`MonitorUpdatingPersister::read_channel_monitor_with_updates`].
303 ///
304 /// ## EXTREMELY IMPORTANT
305 ///
306 /// It is extremely important that your [`KVStore::read`] implementation uses the
307 /// [`io::ErrorKind::NotFound`] variant correctly: that is, when a file is not found, and _only_ in
308 /// that circumstance (not when there is really a permissions error, for example). This is because
309 /// neither channel monitor reading function lists updates. Instead, either reads the monitor, and
310 /// using its stored `update_id`, synthesizes update storage keys, and tries them in sequence until
311 /// one is not found. All _other_ errors will be bubbled up in the function's [`Result`].
312 ///
313 /// # Pruning stale channel updates
314 ///
315 /// Stale updates are pruned when the consolidation threshold is reached according to `maximum_pending_updates`.
316 /// Monitor updates in the range between the latest `update_id` and `update_id - maximum_pending_updates`
317 /// are deleted.
318 /// The `lazy` flag is used on the [`KVStore::remove`] method, so there are no guarantees that the deletions
319 /// will complete. However, stale updates are not a problem for data integrity, since updates are
320 /// only read that are higher than the stored [`ChannelMonitor`]'s `update_id`.
321 ///
322 /// If you have many stale updates stored (such as after a crash with pending lazy deletes), and
323 /// would like to get rid of them, consider using the
324 /// [`MonitorUpdatingPersister::cleanup_stale_updates`] function.
325 #[must_use]
326 #[repr(C)]
327 pub struct MonitorUpdatingPersister {
328         /// A pointer to the opaque Rust object.
329
330         /// Nearly everywhere, inner must be non-null, however in places where
331         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
332         pub inner: *mut nativeMonitorUpdatingPersister,
333         /// Indicates that this is the only struct which contains the same pointer.
334
335         /// Rust functions which take ownership of an object provided via an argument require
336         /// this to be true and invalidate the object pointed to by inner.
337         pub is_owned: bool,
338 }
339
340 impl Drop for MonitorUpdatingPersister {
341         fn drop(&mut self) {
342                 if self.is_owned && !<*mut nativeMonitorUpdatingPersister>::is_null(self.inner) {
343                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
344                 }
345         }
346 }
347 /// Frees any resources used by the MonitorUpdatingPersister, if is_owned is set and inner is non-NULL.
348 #[no_mangle]
349 pub extern "C" fn MonitorUpdatingPersister_free(this_obj: MonitorUpdatingPersister) { }
350 #[allow(unused)]
351 /// Used only if an object of this type is returned as a trait impl by a method
352 pub(crate) extern "C" fn MonitorUpdatingPersister_free_void(this_ptr: *mut c_void) {
353         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMonitorUpdatingPersister) };
354 }
355 #[allow(unused)]
356 impl MonitorUpdatingPersister {
357         pub(crate) fn get_native_ref(&self) -> &'static nativeMonitorUpdatingPersister {
358                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
359         }
360         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMonitorUpdatingPersister {
361                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
362         }
363         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
364         pub(crate) fn take_inner(mut self) -> *mut nativeMonitorUpdatingPersister {
365                 assert!(self.is_owned);
366                 let ret = ObjOps::untweak_ptr(self.inner);
367                 self.inner = core::ptr::null_mut();
368                 ret
369         }
370 }
371 /// Constructs a new [`MonitorUpdatingPersister`].
372 ///
373 /// The `maximum_pending_updates` parameter controls how many updates may be stored before a
374 /// [`MonitorUpdatingPersister`] consolidates updates by writing a full monitor. Note that
375 /// consolidation will frequently occur with fewer updates than what you set here; this number
376 /// is merely the maximum that may be stored. When setting this value, consider that for higher
377 /// values of `maximum_pending_updates`:
378 ///
379 ///   - [`MonitorUpdatingPersister`] will tend to write more [`ChannelMonitorUpdate`]s than
380 /// [`ChannelMonitor`]s, approaching one [`ChannelMonitor`] write for every
381 /// `maximum_pending_updates` [`ChannelMonitorUpdate`]s.
382 ///   - [`MonitorUpdatingPersister`] will issue deletes differently. Lazy deletes will come in
383 /// \"waves\" for each [`ChannelMonitor`] write. A larger `maximum_pending_updates` means bigger,
384 /// less frequent \"waves.\"
385 ///   - [`MonitorUpdatingPersister`] will potentially have more listing to do if you need to run
386 /// [`MonitorUpdatingPersister::cleanup_stale_updates`].
387 #[must_use]
388 #[no_mangle]
389 pub extern "C" fn MonitorUpdatingPersister_new(mut kv_store: crate::lightning::util::persist::KVStore, mut logger: crate::lightning::util::logger::Logger, mut maximum_pending_updates: u64, mut entropy_source: crate::lightning::sign::EntropySource, mut signer_provider: crate::lightning::sign::SignerProvider) -> crate::lightning::util::persist::MonitorUpdatingPersister {
390         let mut ret = lightning::util::persist::MonitorUpdatingPersister::new(kv_store, logger, maximum_pending_updates, entropy_source, signer_provider);
391         crate::lightning::util::persist::MonitorUpdatingPersister { inner: ObjOps::heap_alloc(ret), is_owned: true }
392 }
393
394 /// Reads all stored channel monitors, along with any stored updates for them.
395 ///
396 /// It is extremely important that your [`KVStore::read`] implementation uses the
397 /// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
398 /// documentation for [`MonitorUpdatingPersister`].
399 #[must_use]
400 #[no_mangle]
401 pub extern "C" fn MonitorUpdatingPersister_read_all_channel_monitors_with_updates(this_arg: &crate::lightning::util::persist::MonitorUpdatingPersister, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesChannelMonitorZZIOErrorZ {
402         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_all_channel_monitors_with_updates(broadcaster, fee_estimator);
403         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0_0.as_ref() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_ret_0_0_1), is_owned: true }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() };
404         local_ret
405 }
406
407 /// Read a single channel monitor, along with any stored updates for it.
408 ///
409 /// It is extremely important that your [`KVStore::read`] implementation uses the
410 /// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
411 /// documentation for [`MonitorUpdatingPersister`].
412 ///
413 /// For `monitor_key`, channel storage keys be the channel's transaction ID and index, or
414 /// [`OutPoint`], with an underscore `_` between them. For example, given:
415 ///
416 ///   - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
417 ///   - Index: `1`
418 ///
419 /// The correct `monitor_key` would be:
420 /// `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
421 ///
422 /// Loading a large number of monitors will be faster if done in parallel. You can use this
423 /// function to accomplish this. Take care to limit the number of parallel readers.
424 #[must_use]
425 #[no_mangle]
426 pub extern "C" fn MonitorUpdatingPersister_read_channel_monitor_with_updates(this_arg: &crate::lightning::util::persist::MonitorUpdatingPersister, broadcaster: &crate::lightning::chain::chaininterface::BroadcasterInterface, fee_estimator: &crate::lightning::chain::chaininterface::FeeEstimator, mut monitor_key: crate::c_types::Str) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesChannelMonitorZIOErrorZ {
427         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_channel_monitor_with_updates(broadcaster, fee_estimator, monitor_key.into_string());
428         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0.as_ref() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_ret_0_1), is_owned: true }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() };
429         local_ret
430 }
431
432 /// Cleans up stale updates for all monitors.
433 ///
434 /// This function works by first listing all monitors, and then for each of them, listing all
435 /// updates. The updates that have an `update_id` less than or equal to than the stored monitor
436 /// are deleted. The deletion can either be lazy or non-lazy based on the `lazy` flag; this will
437 /// be passed to [`KVStore::remove`].
438 #[must_use]
439 #[no_mangle]
440 pub extern "C" fn MonitorUpdatingPersister_cleanup_stale_updates(this_arg: &crate::lightning::util::persist::MonitorUpdatingPersister, mut lazy: bool) -> crate::c_types::derived::CResult_NoneIOErrorZ {
441         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.cleanup_stale_updates(lazy);
442         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() };
443         local_ret
444 }
445
446 impl From<nativeMonitorUpdatingPersister> for crate::lightning::chain::chainmonitor::Persist {
447         fn from(obj: nativeMonitorUpdatingPersister) -> Self {
448                 let rust_obj = crate::lightning::util::persist::MonitorUpdatingPersister { inner: ObjOps::heap_alloc(obj), is_owned: true };
449                 let mut ret = MonitorUpdatingPersister_as_Persist(&rust_obj);
450                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
451                 core::mem::forget(rust_obj);
452                 ret.free = Some(MonitorUpdatingPersister_free_void);
453                 ret
454         }
455 }
456 /// Constructs a new Persist which calls the relevant methods on this_arg.
457 /// This copies the `inner` pointer in this_arg and thus the returned Persist must be freed before this_arg is
458 #[no_mangle]
459 pub extern "C" fn MonitorUpdatingPersister_as_Persist(this_arg: &MonitorUpdatingPersister) -> crate::lightning::chain::chainmonitor::Persist {
460         crate::lightning::chain::chainmonitor::Persist {
461                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
462                 free: None,
463                 persist_new_channel: MonitorUpdatingPersister_Persist_persist_new_channel,
464                 update_persisted_channel: MonitorUpdatingPersister_Persist_update_persisted_channel,
465                 archive_persisted_channel: MonitorUpdatingPersister_Persist_archive_persisted_channel,
466         }
467 }
468
469 #[must_use]
470 extern "C" fn MonitorUpdatingPersister_Persist_persist_new_channel(this_arg: *const c_void, mut channel_funding_outpoint: crate::lightning::chain::transaction::OutPoint, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, mut update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus {
471         let mut ret = <nativeMonitorUpdatingPersister as lightning::chain::chainmonitor::Persist<crate::lightning::sign::ecdsa::WriteableEcdsaChannelSigner, >>::persist_new_channel(unsafe { &mut *(this_arg as *mut nativeMonitorUpdatingPersister) }, *unsafe { Box::from_raw(channel_funding_outpoint.take_inner()) }, data.get_native_ref(), *unsafe { Box::from_raw(update_id.take_inner()) });
472         crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(ret)
473 }
474 #[must_use]
475 extern "C" fn MonitorUpdatingPersister_Persist_update_persisted_channel(this_arg: *const c_void, mut channel_funding_outpoint: crate::lightning::chain::transaction::OutPoint, mut update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, mut update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus {
476         let mut local_update = if update.inner.is_null() { None } else { Some( { update.get_native_ref() }) };
477         let mut ret = <nativeMonitorUpdatingPersister as lightning::chain::chainmonitor::Persist<crate::lightning::sign::ecdsa::WriteableEcdsaChannelSigner, >>::update_persisted_channel(unsafe { &mut *(this_arg as *mut nativeMonitorUpdatingPersister) }, *unsafe { Box::from_raw(channel_funding_outpoint.take_inner()) }, local_update, data.get_native_ref(), *unsafe { Box::from_raw(update_id.take_inner()) });
478         crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(ret)
479 }
480 extern "C" fn MonitorUpdatingPersister_Persist_archive_persisted_channel(this_arg: *const c_void, mut channel_funding_outpoint: crate::lightning::chain::transaction::OutPoint) {
481         <nativeMonitorUpdatingPersister as lightning::chain::chainmonitor::Persist<crate::lightning::sign::ecdsa::WriteableEcdsaChannelSigner, >>::archive_persisted_channel(unsafe { &mut *(this_arg as *mut nativeMonitorUpdatingPersister) }, *unsafe { Box::from_raw(channel_funding_outpoint.take_inner()) })
482 }
483