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