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