c71b5c44708bd5b3785a53e2a4c55ad88d4b5903
[ldk-java] / src / main / java / org / ldk / structs / MonitorUpdatingPersister.java
1 package org.ldk.structs;
2
3 import org.ldk.impl.bindings;
4 import org.ldk.enums.*;
5 import org.ldk.util.*;
6 import java.util.Arrays;
7 import java.lang.ref.Reference;
8 import javax.annotation.Nullable;
9
10
11 /**
12  * Implements [`Persist`] in a way that writes and reads both [`ChannelMonitor`]s and
13  * [`ChannelMonitorUpdate`]s.
14  * 
15  * # Overview
16  * 
17  * The main benefit this provides over the [`KVStore`]'s [`Persist`] implementation is decreased
18  * I/O bandwidth and storage churn, at the expense of more IOPS (including listing, reading, and
19  * deleting) and complexity. This is because it writes channel monitor differential updates,
20  * whereas the other (default) implementation rewrites the entire monitor on each update. For
21  * routing nodes, updates can happen many times per second to a channel, and monitors can be tens
22  * of megabytes (or more). Updates can be as small as a few hundred bytes.
23  * 
24  * Note that monitors written with `MonitorUpdatingPersister` are _not_ backward-compatible with
25  * the default [`KVStore`]'s [`Persist`] implementation. They have a prepended byte sequence,
26  * [`MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL`], applied to prevent deserialization with other
27  * persisters. This is because monitors written by this struct _may_ have unapplied updates. In
28  * order to downgrade, you must ensure that all updates are applied to the monitor, and remove the
29  * sentinel bytes.
30  * 
31  * # Storing monitors
32  * 
33  * Monitors are stored by implementing the [`Persist`] trait, which has two functions:
34  * 
35  * - [`Persist::persist_new_channel`], which persists whole [`ChannelMonitor`]s.
36  * - [`Persist::update_persisted_channel`], which persists only a [`ChannelMonitorUpdate`]
37  * 
38  * Whole [`ChannelMonitor`]s are stored in the [`CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE`],
39  * using the familiar encoding of an [`OutPoint`] (for example, `[SOME-64-CHAR-HEX-STRING]_1`).
40  * 
41  * Each [`ChannelMonitorUpdate`] is stored in a dynamic secondary namespace, as follows:
42  * 
43  * - primary namespace: [`CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE`]
44  * - secondary namespace: [the monitor's encoded outpoint name]
45  * 
46  * Under that secondary namespace, each update is stored with a number string, like `21`, which
47  * represents its `update_id` value.
48  * 
49  * For example, consider this channel, named for its transaction ID and index, or [`OutPoint`]:
50  * 
51  * - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
52  * - Index: `1`
53  * 
54  * Full channel monitors would be stored at a single key:
55  * 
56  * `[CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
57  * 
58  * Updates would be stored as follows (with `/` delimiting primary_namespace/secondary_namespace/key):
59  * 
60  * ```text
61  * [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/1
62  * [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/2
63  * [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/3
64  * ```
65  * ... and so on.
66  * 
67  * # Reading channel state from storage
68  * 
69  * Channel state can be reconstructed by calling
70  * [`MonitorUpdatingPersister::read_all_channel_monitors_with_updates`]. Alternatively, users can
71  * list channel monitors themselves and load channels individually using
72  * [`MonitorUpdatingPersister::read_channel_monitor_with_updates`].
73  * 
74  * ## EXTREMELY IMPORTANT
75  * 
76  * It is extremely important that your [`KVStore::read`] implementation uses the
77  * [`io::ErrorKind::NotFound`] variant correctly: that is, when a file is not found, and _only_ in
78  * that circumstance (not when there is really a permissions error, for example). This is because
79  * neither channel monitor reading function lists updates. Instead, either reads the monitor, and
80  * using its stored `update_id`, synthesizes update storage keys, and tries them in sequence until
81  * one is not found. All _other_ errors will be bubbled up in the function's [`Result`].
82  * 
83  * # Pruning stale channel updates
84  * 
85  * Stale updates are pruned when the consolidation threshold is reached according to `maximum_pending_updates`.
86  * Monitor updates in the range between the latest `update_id` and `update_id - maximum_pending_updates`
87  * are deleted.
88  * The `lazy` flag is used on the [`KVStore::remove`] method, so there are no guarantees that the deletions
89  * will complete. However, stale updates are not a problem for data integrity, since updates are
90  * only read that are higher than the stored [`ChannelMonitor`]'s `update_id`.
91  * 
92  * If you have many stale updates stored (such as after a crash with pending lazy deletes), and
93  * would like to get rid of them, consider using the
94  * [`MonitorUpdatingPersister::cleanup_stale_updates`] function.
95  */
96 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
97 public class MonitorUpdatingPersister extends CommonBase {
98         MonitorUpdatingPersister(Object _dummy, long ptr) { super(ptr); }
99         @Override @SuppressWarnings("deprecation")
100         protected void finalize() throws Throwable {
101                 super.finalize();
102                 if (ptr != 0) { bindings.MonitorUpdatingPersister_free(ptr); }
103         }
104
105         /**
106          * Constructs a new [`MonitorUpdatingPersister`].
107          * 
108          * The `maximum_pending_updates` parameter controls how many updates may be stored before a
109          * [`MonitorUpdatingPersister`] consolidates updates by writing a full monitor. Note that
110          * consolidation will frequently occur with fewer updates than what you set here; this number
111          * is merely the maximum that may be stored. When setting this value, consider that for higher
112          * values of `maximum_pending_updates`:
113          * 
114          * - [`MonitorUpdatingPersister`] will tend to write more [`ChannelMonitorUpdate`]s than
115          * [`ChannelMonitor`]s, approaching one [`ChannelMonitor`] write for every
116          * `maximum_pending_updates` [`ChannelMonitorUpdate`]s.
117          * - [`MonitorUpdatingPersister`] will issue deletes differently. Lazy deletes will come in
118          * \"waves\" for each [`ChannelMonitor`] write. A larger `maximum_pending_updates` means bigger,
119          * less frequent \"waves.\"
120          * - [`MonitorUpdatingPersister`] will potentially have more listing to do if you need to run
121          * [`MonitorUpdatingPersister::cleanup_stale_updates`].
122          */
123         public static MonitorUpdatingPersister of(org.ldk.structs.KVStore kv_store, org.ldk.structs.Logger logger, long maximum_pending_updates, org.ldk.structs.EntropySource entropy_source, org.ldk.structs.SignerProvider signer_provider) {
124                 long ret = bindings.MonitorUpdatingPersister_new(kv_store.ptr, logger.ptr, maximum_pending_updates, entropy_source.ptr, signer_provider.ptr);
125                 Reference.reachabilityFence(kv_store);
126                 Reference.reachabilityFence(logger);
127                 Reference.reachabilityFence(maximum_pending_updates);
128                 Reference.reachabilityFence(entropy_source);
129                 Reference.reachabilityFence(signer_provider);
130                 if (ret >= 0 && ret <= 4096) { return null; }
131                 org.ldk.structs.MonitorUpdatingPersister ret_hu_conv = null; if (ret < 0 || ret > 4096) { ret_hu_conv = new org.ldk.structs.MonitorUpdatingPersister(null, ret); }
132                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(ret_hu_conv); };
133                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(kv_store); };
134                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(logger); };
135                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(entropy_source); };
136                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(signer_provider); };
137                 return ret_hu_conv;
138         }
139
140         /**
141          * Reads all stored channel monitors, along with any stored updates for them.
142          * 
143          * It is extremely important that your [`KVStore::read`] implementation uses the
144          * [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
145          * documentation for [`MonitorUpdatingPersister`].
146          */
147         public Result_CVec_C2Tuple_ThirtyTwoBytesChannelMonitorZZIOErrorZ read_all_channel_monitors_with_updates(org.ldk.structs.BroadcasterInterface broadcaster, org.ldk.structs.FeeEstimator fee_estimator) {
148                 long ret = bindings.MonitorUpdatingPersister_read_all_channel_monitors_with_updates(this.ptr, broadcaster.ptr, fee_estimator.ptr);
149                 Reference.reachabilityFence(this);
150                 Reference.reachabilityFence(broadcaster);
151                 Reference.reachabilityFence(fee_estimator);
152                 if (ret >= 0 && ret <= 4096) { return null; }
153                 Result_CVec_C2Tuple_ThirtyTwoBytesChannelMonitorZZIOErrorZ ret_hu_conv = Result_CVec_C2Tuple_ThirtyTwoBytesChannelMonitorZZIOErrorZ.constr_from_ptr(ret);
154                 if (this != null) { this.ptrs_to.add(broadcaster); };
155                 if (this != null) { this.ptrs_to.add(fee_estimator); };
156                 return ret_hu_conv;
157         }
158
159         /**
160          * Read a single channel monitor, along with any stored updates for it.
161          * 
162          * It is extremely important that your [`KVStore::read`] implementation uses the
163          * [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
164          * documentation for [`MonitorUpdatingPersister`].
165          * 
166          * For `monitor_key`, channel storage keys be the channel's transaction ID and index, or
167          * [`OutPoint`], with an underscore `_` between them. For example, given:
168          * 
169          * - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
170          * - Index: `1`
171          * 
172          * The correct `monitor_key` would be:
173          * `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
174          * 
175          * Loading a large number of monitors will be faster if done in parallel. You can use this
176          * function to accomplish this. Take care to limit the number of parallel readers.
177          */
178         public Result_C2Tuple_ThirtyTwoBytesChannelMonitorZIOErrorZ read_channel_monitor_with_updates(org.ldk.structs.BroadcasterInterface broadcaster, org.ldk.structs.FeeEstimator fee_estimator, java.lang.String monitor_key) {
179                 long ret = bindings.MonitorUpdatingPersister_read_channel_monitor_with_updates(this.ptr, broadcaster.ptr, fee_estimator.ptr, monitor_key);
180                 Reference.reachabilityFence(this);
181                 Reference.reachabilityFence(broadcaster);
182                 Reference.reachabilityFence(fee_estimator);
183                 Reference.reachabilityFence(monitor_key);
184                 if (ret >= 0 && ret <= 4096) { return null; }
185                 Result_C2Tuple_ThirtyTwoBytesChannelMonitorZIOErrorZ ret_hu_conv = Result_C2Tuple_ThirtyTwoBytesChannelMonitorZIOErrorZ.constr_from_ptr(ret);
186                 if (this != null) { this.ptrs_to.add(broadcaster); };
187                 if (this != null) { this.ptrs_to.add(fee_estimator); };
188                 return ret_hu_conv;
189         }
190
191         /**
192          * Cleans up stale updates for all monitors.
193          * 
194          * This function works by first listing all monitors, and then for each of them, listing all
195          * updates. The updates that have an `update_id` less than or equal to than the stored monitor
196          * are deleted. The deletion can either be lazy or non-lazy based on the `lazy` flag; this will
197          * be passed to [`KVStore::remove`].
198          */
199         public Result_NoneIOErrorZ cleanup_stale_updates(boolean lazy) {
200                 long ret = bindings.MonitorUpdatingPersister_cleanup_stale_updates(this.ptr, lazy);
201                 Reference.reachabilityFence(this);
202                 Reference.reachabilityFence(lazy);
203                 if (ret >= 0 && ret <= 4096) { return null; }
204                 Result_NoneIOErrorZ ret_hu_conv = Result_NoneIOErrorZ.constr_from_ptr(ret);
205                 return ret_hu_conv;
206         }
207
208         /**
209          * Constructs a new Persist which calls the relevant methods on this_arg.
210          * This copies the `inner` pointer in this_arg and thus the returned Persist must be freed before this_arg is
211          */
212         public Persist as_Persist() {
213                 long ret = bindings.MonitorUpdatingPersister_as_Persist(this.ptr);
214                 Reference.reachabilityFence(this);
215                 if (ret >= 0 && ret <= 4096) { return null; }
216                 Persist ret_hu_conv = new Persist(null, ret);
217                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
218                 return ret_hu_conv;
219         }
220
221 }