Merge pull request #2883 from tnull/2024-02-dyn-kvstore-blanket-impls
[rust-lightning] / lightning / src / util / persist.rs
1 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
2 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
4 // You may not use this file except in accordance with one or both of these
5 // licenses.
6
7 //! This module contains a simple key-value store trait [`KVStore`] that
8 //! allows one to implement the persistence for [`ChannelManager`], [`NetworkGraph`],
9 //! and [`ChannelMonitor`] all in one place.
10
11 use core::cmp;
12 use core::convert::{TryFrom, TryInto};
13 use core::ops::Deref;
14 use core::str::FromStr;
15 use bitcoin::{BlockHash, Txid};
16
17 use crate::{io, log_error};
18 use crate::alloc::string::ToString;
19 use crate::prelude::*;
20
21 use crate::chain;
22 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
23 use crate::chain::chainmonitor::{Persist, MonitorUpdateId};
24 use crate::sign::{EntropySource, NodeSigner, ecdsa::WriteableEcdsaChannelSigner, SignerProvider};
25 use crate::chain::transaction::OutPoint;
26 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, CLOSED_CHANNEL_UPDATE_ID};
27 use crate::ln::channelmanager::ChannelManager;
28 use crate::routing::router::Router;
29 use crate::routing::gossip::NetworkGraph;
30 use crate::routing::scoring::WriteableScore;
31 use crate::util::logger::Logger;
32 use crate::util::ser::{Readable, ReadableArgs, Writeable};
33
34 /// The alphabet of characters allowed for namespaces and keys.
35 pub const KVSTORE_NAMESPACE_KEY_ALPHABET: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
36
37 /// The maximum number of characters namespaces and keys may have.
38 pub const KVSTORE_NAMESPACE_KEY_MAX_LEN: usize = 120;
39
40 /// The primary namespace under which the [`ChannelManager`] will be persisted.
41 pub const CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
42 /// The secondary namespace under which the [`ChannelManager`] will be persisted.
43 pub const CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
44 /// The key under which the [`ChannelManager`] will be persisted.
45 pub const CHANNEL_MANAGER_PERSISTENCE_KEY: &str = "manager";
46
47 /// The primary namespace under which [`ChannelMonitor`]s will be persisted.
48 pub const CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE: &str = "monitors";
49 /// The secondary namespace under which [`ChannelMonitor`]s will be persisted.
50 pub const CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
51 /// The primary namespace under which [`ChannelMonitorUpdate`]s will be persisted.
52 pub const CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE: &str = "monitor_updates";
53
54 /// The primary namespace under which the [`NetworkGraph`] will be persisted.
55 pub const NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
56 /// The secondary namespace under which the [`NetworkGraph`] will be persisted.
57 pub const NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
58 /// The key under which the [`NetworkGraph`] will be persisted.
59 pub const NETWORK_GRAPH_PERSISTENCE_KEY: &str = "network_graph";
60
61 /// The primary namespace under which the [`WriteableScore`] will be persisted.
62 pub const SCORER_PERSISTENCE_PRIMARY_NAMESPACE: &str = "";
63 /// The secondary namespace under which the [`WriteableScore`] will be persisted.
64 pub const SCORER_PERSISTENCE_SECONDARY_NAMESPACE: &str = "";
65 /// The key under which the [`WriteableScore`] will be persisted.
66 pub const SCORER_PERSISTENCE_KEY: &str = "scorer";
67
68 /// A sentinel value to be prepended to monitors persisted by the [`MonitorUpdatingPersister`].
69 ///
70 /// This serves to prevent someone from accidentally loading such monitors (which may need
71 /// updates applied to be current) with another implementation.
72 pub const MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL: &[u8] = &[0xFF; 2];
73
74 /// Provides an interface that allows storage and retrieval of persisted values that are associated
75 /// with given keys.
76 ///
77 /// In order to avoid collisions the key space is segmented based on the given `primary_namespace`s
78 /// and `secondary_namespace`s. Implementations of this trait are free to handle them in different
79 /// ways, as long as per-namespace key uniqueness is asserted.
80 ///
81 /// Keys and namespaces are required to be valid ASCII strings in the range of
82 /// [`KVSTORE_NAMESPACE_KEY_ALPHABET`] and no longer than [`KVSTORE_NAMESPACE_KEY_MAX_LEN`]. Empty
83 /// primary namespaces and secondary namespaces (`""`) are assumed to be a valid, however, if
84 /// `primary_namespace` is empty, `secondary_namespace` is required to be empty, too. This means
85 /// that concerns should always be separated by primary namespace first, before secondary
86 /// namespaces are used. While the number of primary namespaces will be relatively small and is
87 /// determined at compile time, there may be many secondary namespaces per primary namespace. Note
88 /// that per-namespace uniqueness needs to also hold for keys *and* namespaces in any given
89 /// namespace, i.e., conflicts between keys and equally named
90 /// primary namespaces/secondary namespaces must be avoided.
91 ///
92 /// **Note:** Users migrating custom persistence backends from the pre-v0.0.117 `KVStorePersister`
93 /// interface can use a concatenation of `[{primary_namespace}/[{secondary_namespace}/]]{key}` to
94 /// recover a `key` compatible with the data model previously assumed by `KVStorePersister::persist`.
95 pub trait KVStore {
96         /// Returns the data stored for the given `primary_namespace`, `secondary_namespace`, and
97         /// `key`.
98         ///
99         /// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given
100         /// `primary_namespace` and `secondary_namespace`.
101         ///
102         /// [`ErrorKind::NotFound`]: io::ErrorKind::NotFound
103         fn read(&self, primary_namespace: &str, secondary_namespace: &str, key: &str) -> Result<Vec<u8>, io::Error>;
104         /// Persists the given data under the given `key`.
105         ///
106         /// Will create the given `primary_namespace` and `secondary_namespace` if not already present
107         /// in the store.
108         fn write(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, buf: &[u8]) -> Result<(), io::Error>;
109         /// Removes any data that had previously been persisted under the given `key`.
110         ///
111         /// If the `lazy` flag is set to `true`, the backend implementation might choose to lazily
112         /// remove the given `key` at some point in time after the method returns, e.g., as part of an
113         /// eventual batch deletion of multiple keys. As a consequence, subsequent calls to
114         /// [`KVStore::list`] might include the removed key until the changes are actually persisted.
115         ///
116         /// Note that while setting the `lazy` flag reduces the I/O burden of multiple subsequent
117         /// `remove` calls, it also influences the atomicity guarantees as lazy `remove`s could
118         /// potentially get lost on crash after the method returns. Therefore, this flag should only be
119         /// set for `remove` operations that can be safely replayed at a later time.
120         ///
121         /// Returns successfully if no data will be stored for the given `primary_namespace`,
122         /// `secondary_namespace`, and `key`, independently of whether it was present before its
123         /// invokation or not.
124         fn remove(&self, primary_namespace: &str, secondary_namespace: &str, key: &str, lazy: bool) -> Result<(), io::Error>;
125         /// Returns a list of keys that are stored under the given `secondary_namespace` in
126         /// `primary_namespace`.
127         ///
128         /// Returns the keys in arbitrary order, so users requiring a particular order need to sort the
129         /// returned keys. Returns an empty list if `primary_namespace` or `secondary_namespace` is unknown.
130         fn list(&self, primary_namespace: &str, secondary_namespace: &str) -> Result<Vec<String>, io::Error>;
131 }
132
133 /// Trait that handles persisting a [`ChannelManager`], [`NetworkGraph`], and [`WriteableScore`] to disk.
134 pub trait Persister<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>>
135         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
136                 T::Target: 'static + BroadcasterInterface,
137                 ES::Target: 'static + EntropySource,
138                 NS::Target: 'static + NodeSigner,
139                 SP::Target: 'static + SignerProvider,
140                 F::Target: 'static + FeeEstimator,
141                 R::Target: 'static + Router,
142                 L::Target: 'static + Logger,
143 {
144         /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed.
145         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error>;
146
147         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
148         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error>;
149
150         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
151         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error>;
152 }
153
154
155 impl<'a, A: KVStore, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>> Persister<'a, M, T, ES, NS, SP, F, R, L, S> for A
156         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
157                 T::Target: 'static + BroadcasterInterface,
158                 ES::Target: 'static + EntropySource,
159                 NS::Target: 'static + NodeSigner,
160                 SP::Target: 'static + SignerProvider,
161                 F::Target: 'static + FeeEstimator,
162                 R::Target: 'static + Router,
163                 L::Target: 'static + Logger,
164 {
165         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed.
166         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error> {
167                 self.write(CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
168                         CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
169                         CHANNEL_MANAGER_PERSISTENCE_KEY,
170                         &channel_manager.encode())
171         }
172
173         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
174         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error> {
175                 self.write(NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
176                         NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
177                         NETWORK_GRAPH_PERSISTENCE_KEY,
178                         &network_graph.encode())
179         }
180
181         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
182         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error> {
183                 self.write(SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
184                         SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
185                         SCORER_PERSISTENCE_KEY,
186                         &scorer.encode())
187         }
188 }
189
190 impl<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>> Persister<'a, M, T, ES, NS, SP, F, R, L, S> for dyn KVStore + Send + Sync
191         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
192                 T::Target: 'static + BroadcasterInterface,
193                 ES::Target: 'static + EntropySource,
194                 NS::Target: 'static + NodeSigner,
195                 SP::Target: 'static + SignerProvider,
196                 F::Target: 'static + FeeEstimator,
197                 R::Target: 'static + Router,
198                 L::Target: 'static + Logger,
199 {
200         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed.
201         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error> {
202                 self.write(CHANNEL_MANAGER_PERSISTENCE_PRIMARY_NAMESPACE,
203                         CHANNEL_MANAGER_PERSISTENCE_SECONDARY_NAMESPACE,
204                         CHANNEL_MANAGER_PERSISTENCE_KEY,
205                         &channel_manager.encode())
206         }
207
208         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
209         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error> {
210                 self.write(NETWORK_GRAPH_PERSISTENCE_PRIMARY_NAMESPACE,
211                         NETWORK_GRAPH_PERSISTENCE_SECONDARY_NAMESPACE,
212                         NETWORK_GRAPH_PERSISTENCE_KEY,
213                         &network_graph.encode())
214         }
215
216         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
217         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error> {
218                 self.write(SCORER_PERSISTENCE_PRIMARY_NAMESPACE,
219                         SCORER_PERSISTENCE_SECONDARY_NAMESPACE,
220                         SCORER_PERSISTENCE_KEY,
221                         &scorer.encode())
222         }
223 }
224
225 impl<ChannelSigner: WriteableEcdsaChannelSigner, K: KVStore> Persist<ChannelSigner> for K {
226         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
227         // down once these start returning failure.
228         // Then we should return InProgress rather than UnrecoverableError, implying we should probably
229         // just shut down the node since we're not retrying persistence!
230
231         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
232                 let key = format!("{}_{}", funding_txo.txid.to_string(), funding_txo.index);
233                 match self.write(
234                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
235                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
236                         &key, &monitor.encode())
237                 {
238                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
239                         Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError
240                 }
241         }
242
243         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
244                 let key = format!("{}_{}", funding_txo.txid.to_string(), funding_txo.index);
245                 match self.write(
246                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
247                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
248                         &key, &monitor.encode())
249                 {
250                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
251                         Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError
252                 }
253         }
254 }
255
256 impl<ChannelSigner: WriteableEcdsaChannelSigner> Persist<ChannelSigner> for dyn KVStore + Send + Sync {
257         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
258         // down once these start returning failure.
259         // Then we should return InProgress rather than UnrecoverableError, implying we should probably
260         // just shut down the node since we're not retrying persistence!
261
262         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
263                 let key = format!("{}_{}", funding_txo.txid.to_string(), funding_txo.index);
264                 match self.write(
265                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
266                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
267                         &key, &monitor.encode())
268                 {
269                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
270                         Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError
271                 }
272         }
273
274         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
275                 let key = format!("{}_{}", funding_txo.txid.to_string(), funding_txo.index);
276                 match self.write(
277                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
278                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
279                         &key, &monitor.encode())
280                 {
281                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
282                         Err(_) => chain::ChannelMonitorUpdateStatus::UnrecoverableError
283                 }
284         }
285 }
286
287 /// Read previously persisted [`ChannelMonitor`]s from the store.
288 pub fn read_channel_monitors<K: Deref, ES: Deref, SP: Deref>(
289         kv_store: K, entropy_source: ES, signer_provider: SP,
290 ) -> Result<Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>, io::Error>
291 where
292         K::Target: KVStore,
293         ES::Target: EntropySource + Sized,
294         SP::Target: SignerProvider + Sized,
295 {
296         let mut res = Vec::new();
297
298         for stored_key in kv_store.list(
299                 CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE)?
300         {
301                 if stored_key.len() < 66 {
302                         return Err(io::Error::new(
303                                 io::ErrorKind::InvalidData,
304                                 "Stored key has invalid length"));
305                 }
306
307                 let txid = Txid::from_str(stored_key.split_at(64).0).map_err(|_| {
308                         io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
309                 })?;
310
311                 let index: u16 = stored_key.split_at(65).1.parse().map_err(|_| {
312                         io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
313                 })?;
314
315                 match <(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>::read(
316                         &mut io::Cursor::new(
317                                 kv_store.read(CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE, &stored_key)?),
318                         (&*entropy_source, &*signer_provider),
319                 ) {
320                         Ok((block_hash, channel_monitor)) => {
321                                 if channel_monitor.get_funding_txo().0.txid != txid
322                                         || channel_monitor.get_funding_txo().0.index != index
323                                 {
324                                         return Err(io::Error::new(
325                                                 io::ErrorKind::InvalidData,
326                                                 "ChannelMonitor was stored under the wrong key",
327                                         ));
328                                 }
329                                 res.push((block_hash, channel_monitor));
330                         }
331                         Err(_) => {
332                                 return Err(io::Error::new(
333                                         io::ErrorKind::InvalidData,
334                                         "Failed to read ChannelMonitor"
335                                 ))
336                         }
337                 }
338         }
339         Ok(res)
340 }
341
342 /// Implements [`Persist`] in a way that writes and reads both [`ChannelMonitor`]s and
343 /// [`ChannelMonitorUpdate`]s.
344 ///
345 /// # Overview
346 ///
347 /// The main benefit this provides over the [`KVStore`]'s [`Persist`] implementation is decreased
348 /// I/O bandwidth and storage churn, at the expense of more IOPS (including listing, reading, and
349 /// deleting) and complexity. This is because it writes channel monitor differential updates,
350 /// whereas the other (default) implementation rewrites the entire monitor on each update. For
351 /// routing nodes, updates can happen many times per second to a channel, and monitors can be tens
352 /// of megabytes (or more). Updates can be as small as a few hundred bytes.
353 ///
354 /// Note that monitors written with `MonitorUpdatingPersister` are _not_ backward-compatible with
355 /// the default [`KVStore`]'s [`Persist`] implementation. They have a prepended byte sequence,
356 /// [`MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL`], applied to prevent deserialization with other
357 /// persisters. This is because monitors written by this struct _may_ have unapplied updates. In
358 /// order to downgrade, you must ensure that all updates are applied to the monitor, and remove the
359 /// sentinel bytes.
360 ///
361 /// # Storing monitors
362 ///
363 /// Monitors are stored by implementing the [`Persist`] trait, which has two functions:
364 ///
365 ///   - [`Persist::persist_new_channel`], which persists whole [`ChannelMonitor`]s.
366 ///   - [`Persist::update_persisted_channel`], which persists only a [`ChannelMonitorUpdate`]
367 ///
368 /// Whole [`ChannelMonitor`]s are stored in the [`CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE`],
369 /// using the familiar encoding of an [`OutPoint`] (for example, `[SOME-64-CHAR-HEX-STRING]_1`).
370 ///
371 /// Each [`ChannelMonitorUpdate`] is stored in a dynamic secondary namespace, as follows:
372 ///
373 ///   - primary namespace: [`CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE`]
374 ///   - secondary namespace: [the monitor's encoded outpoint name]
375 ///
376 /// Under that secondary namespace, each update is stored with a number string, like `21`, which
377 /// represents its `update_id` value.
378 ///
379 /// For example, consider this channel, named for its transaction ID and index, or [`OutPoint`]:
380 ///
381 ///   - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
382 ///   - Index: `1`
383 ///
384 /// Full channel monitors would be stored at a single key:
385 ///
386 /// `[CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
387 ///
388 /// Updates would be stored as follows (with `/` delimiting primary_namespace/secondary_namespace/key):
389 ///
390 /// ```text
391 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/1
392 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/2
393 /// [CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE]/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1/3
394 /// ```
395 /// ... and so on.
396 ///
397 /// # Reading channel state from storage
398 ///
399 /// Channel state can be reconstructed by calling
400 /// [`MonitorUpdatingPersister::read_all_channel_monitors_with_updates`]. Alternatively, users can
401 /// list channel monitors themselves and load channels individually using
402 /// [`MonitorUpdatingPersister::read_channel_monitor_with_updates`].
403 ///
404 /// ## EXTREMELY IMPORTANT
405 ///
406 /// It is extremely important that your [`KVStore::read`] implementation uses the
407 /// [`io::ErrorKind::NotFound`] variant correctly: that is, when a file is not found, and _only_ in
408 /// that circumstance (not when there is really a permissions error, for example). This is because
409 /// neither channel monitor reading function lists updates. Instead, either reads the monitor, and
410 /// using its stored `update_id`, synthesizes update storage keys, and tries them in sequence until
411 /// one is not found. All _other_ errors will be bubbled up in the function's [`Result`].
412 ///
413 /// # Pruning stale channel updates
414 ///
415 /// Stale updates are pruned when the consolidation threshold is reached according to `maximum_pending_updates`.
416 /// Monitor updates in the range between the latest `update_id` and `update_id - maximum_pending_updates`
417 /// are deleted.
418 /// The `lazy` flag is used on the [`KVStore::remove`] method, so there are no guarantees that the deletions
419 /// will complete. However, stale updates are not a problem for data integrity, since updates are
420 /// only read that are higher than the stored [`ChannelMonitor`]'s `update_id`.
421 ///
422 /// If you have many stale updates stored (such as after a crash with pending lazy deletes), and
423 /// would like to get rid of them, consider using the
424 /// [`MonitorUpdatingPersister::cleanup_stale_updates`] function.
425 pub struct MonitorUpdatingPersister<K: Deref, L: Deref, ES: Deref, SP: Deref>
426 where
427         K::Target: KVStore,
428         L::Target: Logger,
429         ES::Target: EntropySource + Sized,
430         SP::Target: SignerProvider + Sized,
431 {
432         kv_store: K,
433         logger: L,
434         maximum_pending_updates: u64,
435         entropy_source: ES,
436         signer_provider: SP,
437 }
438
439 #[allow(dead_code)]
440 impl<K: Deref, L: Deref, ES: Deref, SP: Deref>
441         MonitorUpdatingPersister<K, L, ES, SP>
442 where
443         K::Target: KVStore,
444         L::Target: Logger,
445         ES::Target: EntropySource + Sized,
446         SP::Target: SignerProvider + Sized,
447 {
448         /// Constructs a new [`MonitorUpdatingPersister`].
449         ///
450         /// The `maximum_pending_updates` parameter controls how many updates may be stored before a
451         /// [`MonitorUpdatingPersister`] consolidates updates by writing a full monitor. Note that
452         /// consolidation will frequently occur with fewer updates than what you set here; this number
453         /// is merely the maximum that may be stored. When setting this value, consider that for higher
454         /// values of `maximum_pending_updates`:
455         ///
456         ///   - [`MonitorUpdatingPersister`] will tend to write more [`ChannelMonitorUpdate`]s than
457         /// [`ChannelMonitor`]s, approaching one [`ChannelMonitor`] write for every
458         /// `maximum_pending_updates` [`ChannelMonitorUpdate`]s.
459         ///   - [`MonitorUpdatingPersister`] will issue deletes differently. Lazy deletes will come in
460         /// "waves" for each [`ChannelMonitor`] write. A larger `maximum_pending_updates` means bigger,
461         /// less frequent "waves."
462         ///   - [`MonitorUpdatingPersister`] will potentially have more listing to do if you need to run
463         /// [`MonitorUpdatingPersister::cleanup_stale_updates`].
464         pub fn new(
465                 kv_store: K, logger: L, maximum_pending_updates: u64, entropy_source: ES,
466                 signer_provider: SP,
467         ) -> Self {
468                 MonitorUpdatingPersister {
469                         kv_store,
470                         logger,
471                         maximum_pending_updates,
472                         entropy_source,
473                         signer_provider,
474                 }
475         }
476
477         /// Reads all stored channel monitors, along with any stored updates for them.
478         ///
479         /// It is extremely important that your [`KVStore::read`] implementation uses the
480         /// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
481         /// documentation for [`MonitorUpdatingPersister`].
482         pub fn read_all_channel_monitors_with_updates<B: Deref, F: Deref>(
483                 &self, broadcaster: &B, fee_estimator: &F,
484         ) -> Result<Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>, io::Error>
485         where
486                 B::Target: BroadcasterInterface,
487                 F::Target: FeeEstimator,
488         {
489                 let monitor_list = self.kv_store.list(
490                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
491                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
492                 )?;
493                 let mut res = Vec::with_capacity(monitor_list.len());
494                 for monitor_key in monitor_list {
495                         res.push(self.read_channel_monitor_with_updates(
496                                 broadcaster,
497                                 fee_estimator,
498                                 monitor_key,
499                         )?)
500                 }
501                 Ok(res)
502         }
503
504         /// Read a single channel monitor, along with any stored updates for it.
505         ///
506         /// It is extremely important that your [`KVStore::read`] implementation uses the
507         /// [`io::ErrorKind::NotFound`] variant correctly. For more information, please see the
508         /// documentation for [`MonitorUpdatingPersister`].
509         ///
510         /// For `monitor_key`, channel storage keys be the channel's transaction ID and index, or
511         /// [`OutPoint`], with an underscore `_` between them. For example, given:
512         ///
513         ///   - Transaction ID: `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef`
514         ///   - Index: `1`
515         ///
516         /// The correct `monitor_key` would be:
517         /// `deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1`
518         ///
519         /// Loading a large number of monitors will be faster if done in parallel. You can use this
520         /// function to accomplish this. Take care to limit the number of parallel readers.
521         pub fn read_channel_monitor_with_updates<B: Deref, F: Deref>(
522                 &self, broadcaster: &B, fee_estimator: &F, monitor_key: String,
523         ) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error>
524         where
525                 B::Target: BroadcasterInterface,
526                 F::Target: FeeEstimator,
527         {
528                 let monitor_name = MonitorName::new(monitor_key)?;
529                 let (block_hash, monitor) = self.read_monitor(&monitor_name)?;
530                 let mut current_update_id = monitor.get_latest_update_id();
531                 loop {
532                         current_update_id = match current_update_id.checked_add(1) {
533                                 Some(next_update_id) => next_update_id,
534                                 None => break,
535                         };
536                         let update_name = UpdateName::from(current_update_id);
537                         let update = match self.read_monitor_update(&monitor_name, &update_name) {
538                                 Ok(update) => update,
539                                 Err(err) if err.kind() == io::ErrorKind::NotFound => {
540                                         // We can't find any more updates, so we are done.
541                                         break;
542                                 }
543                                 Err(err) => return Err(err),
544                         };
545
546                         monitor.update_monitor(&update, broadcaster, fee_estimator, &self.logger)
547                                 .map_err(|e| {
548                                         log_error!(
549                                                 self.logger,
550                                                 "Monitor update failed. monitor: {} update: {} reason: {:?}",
551                                                 monitor_name.as_str(),
552                                                 update_name.as_str(),
553                                                 e
554                                         );
555                                         io::Error::new(io::ErrorKind::Other, "Monitor update failed")
556                                 })?;
557                 }
558                 Ok((block_hash, monitor))
559         }
560
561         /// Read a channel monitor.
562         fn read_monitor(
563                 &self, monitor_name: &MonitorName,
564         ) -> Result<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>), io::Error> {
565                 let outpoint: OutPoint = monitor_name.try_into()?;
566                 let mut monitor_cursor = io::Cursor::new(self.kv_store.read(
567                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
568                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
569                         monitor_name.as_str(),
570                 )?);
571                 // Discard the sentinel bytes if found.
572                 if monitor_cursor.get_ref().starts_with(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL) {
573                         monitor_cursor.set_position(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() as u64);
574                 }
575                 match <(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::EcdsaSigner>)>::read(
576                         &mut monitor_cursor,
577                         (&*self.entropy_source, &*self.signer_provider),
578                 ) {
579                         Ok((blockhash, channel_monitor)) => {
580                                 if channel_monitor.get_funding_txo().0.txid != outpoint.txid
581                                         || channel_monitor.get_funding_txo().0.index != outpoint.index
582                                 {
583                                         log_error!(
584                                                 self.logger,
585                                                 "ChannelMonitor {} was stored under the wrong key!",
586                                                 monitor_name.as_str()
587                                         );
588                                         Err(io::Error::new(
589                                                 io::ErrorKind::InvalidData,
590                                                 "ChannelMonitor was stored under the wrong key",
591                                         ))
592                                 } else {
593                                         Ok((blockhash, channel_monitor))
594                                 }
595                         }
596                         Err(e) => {
597                                 log_error!(
598                                         self.logger,
599                                         "Failed to read ChannelMonitor {}, reason: {}",
600                                         monitor_name.as_str(),
601                                         e,
602                                 );
603                                 Err(io::Error::new(io::ErrorKind::InvalidData, "Failed to read ChannelMonitor"))
604                         }
605                 }
606         }
607
608         /// Read a channel monitor update.
609         fn read_monitor_update(
610                 &self, monitor_name: &MonitorName, update_name: &UpdateName,
611         ) -> Result<ChannelMonitorUpdate, io::Error> {
612                 let update_bytes = self.kv_store.read(
613                         CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
614                         monitor_name.as_str(),
615                         update_name.as_str(),
616                 )?;
617                 ChannelMonitorUpdate::read(&mut io::Cursor::new(update_bytes)).map_err(|e| {
618                         log_error!(
619                                 self.logger,
620                                 "Failed to read ChannelMonitorUpdate {}/{}/{}, reason: {}",
621                                 CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
622                                 monitor_name.as_str(),
623                                 update_name.as_str(),
624                                 e,
625                         );
626                         io::Error::new(io::ErrorKind::InvalidData, "Failed to read ChannelMonitorUpdate")
627                 })
628         }
629
630         /// Cleans up stale updates for all monitors.
631         ///
632         /// This function works by first listing all monitors, and then for each of them, listing all
633         /// updates. The updates that have an `update_id` less than or equal to than the stored monitor
634         /// are deleted. The deletion can either be lazy or non-lazy based on the `lazy` flag; this will
635         /// be passed to [`KVStore::remove`].
636         pub fn cleanup_stale_updates(&self, lazy: bool) -> Result<(), io::Error> {
637                 let monitor_keys = self.kv_store.list(
638                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
639                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
640                 )?;
641                 for monitor_key in monitor_keys {
642                         let monitor_name = MonitorName::new(monitor_key)?;
643                         let (_, current_monitor) = self.read_monitor(&monitor_name)?;
644                         let updates = self
645                                 .kv_store
646                                 .list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str())?;
647                         for update in updates {
648                                 let update_name = UpdateName::new(update)?;
649                                 // if the update_id is lower than the stored monitor, delete
650                                 if update_name.0 <= current_monitor.get_latest_update_id() {
651                                         self.kv_store.remove(
652                                                 CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
653                                                 monitor_name.as_str(),
654                                                 update_name.as_str(),
655                                                 lazy,
656                                         )?;
657                                 }
658                         }
659                 }
660                 Ok(())
661         }
662 }
663
664 impl<ChannelSigner: WriteableEcdsaChannelSigner, K: Deref, L: Deref, ES: Deref, SP: Deref>
665         Persist<ChannelSigner> for MonitorUpdatingPersister<K, L, ES, SP>
666 where
667         K::Target: KVStore,
668         L::Target: Logger,
669         ES::Target: EntropySource + Sized,
670         SP::Target: SignerProvider + Sized,
671 {
672         /// Persists a new channel. This means writing the entire monitor to the
673         /// parametrized [`KVStore`].
674         fn persist_new_channel(
675                 &self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>,
676                 _monitor_update_call_id: MonitorUpdateId,
677         ) -> chain::ChannelMonitorUpdateStatus {
678                 // Determine the proper key for this monitor
679                 let monitor_name = MonitorName::from(funding_txo);
680                 // Serialize and write the new monitor
681                 let mut monitor_bytes = Vec::with_capacity(
682                         MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL.len() + monitor.serialized_length(),
683                 );
684                 monitor_bytes.extend_from_slice(MONITOR_UPDATING_PERSISTER_PREPEND_SENTINEL);
685                 monitor.write(&mut monitor_bytes).unwrap();
686                 match self.kv_store.write(
687                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
688                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
689                         monitor_name.as_str(),
690                         &monitor_bytes,
691                 ) {
692                         Ok(_) => {
693                                 chain::ChannelMonitorUpdateStatus::Completed
694                         }
695                         Err(e) => {
696                                 log_error!(
697                                         self.logger,
698                                         "Failed to write ChannelMonitor {}/{}/{} reason: {}",
699                                         CHANNEL_MONITOR_PERSISTENCE_PRIMARY_NAMESPACE,
700                                         CHANNEL_MONITOR_PERSISTENCE_SECONDARY_NAMESPACE,
701                                         monitor_name.as_str(),
702                                         e
703                                 );
704                                 chain::ChannelMonitorUpdateStatus::UnrecoverableError
705                         }
706                 }
707         }
708
709         /// Persists a channel update, writing only the update to the parameterized [`KVStore`] if possible.
710         ///
711         /// In some cases, this will forward to [`MonitorUpdatingPersister::persist_new_channel`]:
712         ///
713         ///   - No full monitor is found in [`KVStore`]
714         ///   - The number of pending updates exceeds `maximum_pending_updates` as given to [`Self::new`]
715         ///   - LDK commands re-persisting the entire monitor through this function, specifically when
716         ///     `update` is `None`.
717         ///   - The update is at [`CLOSED_CHANNEL_UPDATE_ID`]
718         fn update_persisted_channel(
719                 &self, funding_txo: OutPoint, update: Option<&ChannelMonitorUpdate>,
720                 monitor: &ChannelMonitor<ChannelSigner>, monitor_update_call_id: MonitorUpdateId,
721         ) -> chain::ChannelMonitorUpdateStatus {
722                 // IMPORTANT: monitor_update_call_id: MonitorUpdateId is not to be confused with
723                 // ChannelMonitorUpdate's update_id.
724                 if let Some(update) = update {
725                         if update.update_id != CLOSED_CHANNEL_UPDATE_ID
726                                 && update.update_id % self.maximum_pending_updates != 0
727                         {
728                                 let monitor_name = MonitorName::from(funding_txo);
729                                 let update_name = UpdateName::from(update.update_id);
730                                 match self.kv_store.write(
731                                         CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
732                                         monitor_name.as_str(),
733                                         update_name.as_str(),
734                                         &update.encode(),
735                                 ) {
736                                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
737                                         Err(e) => {
738                                                 log_error!(
739                                                         self.logger,
740                                                         "Failed to write ChannelMonitorUpdate {}/{}/{} reason: {}",
741                                                         CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
742                                                         monitor_name.as_str(),
743                                                         update_name.as_str(),
744                                                         e
745                                                 );
746                                                 chain::ChannelMonitorUpdateStatus::UnrecoverableError
747                                         }
748                                 }
749                         } else {
750                                 let monitor_name = MonitorName::from(funding_txo);
751                                 // In case of channel-close monitor update, we need to read old monitor before persisting
752                                 // the new one in order to determine the cleanup range.
753                                 let maybe_old_monitor = match monitor.get_latest_update_id() {
754                                         CLOSED_CHANNEL_UPDATE_ID => self.read_monitor(&monitor_name).ok(),
755                                         _ => None
756                                 };
757
758                                 // We could write this update, but it meets criteria of our design that calls for a full monitor write.
759                                 let monitor_update_status = self.persist_new_channel(funding_txo, monitor, monitor_update_call_id);
760
761                                 if let chain::ChannelMonitorUpdateStatus::Completed = monitor_update_status {
762                                         let cleanup_range = if monitor.get_latest_update_id() == CLOSED_CHANNEL_UPDATE_ID {
763                                                 // If there is an error while reading old monitor, we skip clean up.
764                                                 maybe_old_monitor.map(|(_, ref old_monitor)| {
765                                                         let start = old_monitor.get_latest_update_id();
766                                                         // We never persist an update with update_id = CLOSED_CHANNEL_UPDATE_ID
767                                                         let end = cmp::min(
768                                                                 start.saturating_add(self.maximum_pending_updates),
769                                                                 CLOSED_CHANNEL_UPDATE_ID - 1,
770                                                         );
771                                                         (start, end)
772                                                 })
773                                         } else {
774                                                 let end = monitor.get_latest_update_id();
775                                                 let start = end.saturating_sub(self.maximum_pending_updates);
776                                                 Some((start, end))
777                                         };
778
779                                         if let Some((start, end)) = cleanup_range {
780                                                 self.cleanup_in_range(monitor_name, start, end);
781                                         }
782                                 }
783
784                                 monitor_update_status
785                         }
786                 } else {
787                         // There is no update given, so we must persist a new monitor.
788                         self.persist_new_channel(funding_txo, monitor, monitor_update_call_id)
789                 }
790         }
791 }
792
793 impl<K: Deref, L: Deref, ES: Deref, SP: Deref> MonitorUpdatingPersister<K, L, ES, SP>
794 where
795         ES::Target: EntropySource + Sized,
796         K::Target: KVStore,
797         L::Target: Logger,
798         SP::Target: SignerProvider + Sized
799 {
800         // Cleans up monitor updates for given monitor in range `start..=end`.
801         fn cleanup_in_range(&self, monitor_name: MonitorName, start: u64, end: u64) {
802                 for update_id in start..=end {
803                         let update_name = UpdateName::from(update_id);
804                         if let Err(e) = self.kv_store.remove(
805                                 CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
806                                 monitor_name.as_str(),
807                                 update_name.as_str(),
808                                 true,
809                         ) {
810                                 log_error!(
811                                         self.logger,
812                                         "Failed to clean up channel monitor updates for monitor {}, reason: {}",
813                                         monitor_name.as_str(),
814                                         e
815                                 );
816                         };
817                 }
818         }
819 }
820
821 /// A struct representing a name for a monitor.
822 #[derive(Debug)]
823 struct MonitorName(String);
824
825 impl MonitorName {
826         /// Constructs a [`MonitorName`], after verifying that an [`OutPoint`] can
827         /// be formed from the given `name`.
828         pub fn new(name: String) -> Result<Self, io::Error> {
829                 MonitorName::do_try_into_outpoint(&name)?;
830                 Ok(Self(name))
831         }
832         /// Convert this monitor name to a str.
833         pub fn as_str(&self) -> &str {
834                 &self.0
835         }
836         /// Attempt to form a valid [`OutPoint`] from a given name string.
837         fn do_try_into_outpoint(name: &str) -> Result<OutPoint, io::Error> {
838                 let mut parts = name.splitn(2, '_');
839                 let txid = if let Some(part) = parts.next() {
840                         Txid::from_str(part).map_err(|_| {
841                                 io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
842                         })?
843                 } else {
844                         return Err(io::Error::new(
845                                 io::ErrorKind::InvalidData,
846                                 "Stored monitor key is not a splittable string",
847                         ));
848                 };
849                 let index = if let Some(part) = parts.next() {
850                         part.parse().map_err(|_| {
851                                 io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
852                         })?
853                 } else {
854                         return Err(io::Error::new(
855                                 io::ErrorKind::InvalidData,
856                                 "No tx index value found after underscore in stored key",
857                         ));
858                 };
859                 Ok(OutPoint { txid, index })
860         }
861 }
862
863 impl TryFrom<&MonitorName> for OutPoint {
864         type Error = io::Error;
865
866         fn try_from(value: &MonitorName) -> Result<Self, io::Error> {
867                 MonitorName::do_try_into_outpoint(&value.0)
868         }
869 }
870
871 impl From<OutPoint> for MonitorName {
872         fn from(value: OutPoint) -> Self {
873                 MonitorName(format!("{}_{}", value.txid.to_string(), value.index))
874         }
875 }
876
877 /// A struct representing a name for an update.
878 #[derive(Debug)]
879 struct UpdateName(u64, String);
880
881 impl UpdateName {
882         /// Constructs an [`UpdateName`], after verifying that an update sequence ID
883         /// can be derived from the given `name`.
884         pub fn new(name: String) -> Result<Self, io::Error> {
885                 match name.parse::<u64>() {
886                         Ok(u) => Ok(u.into()),
887                         Err(_) => {
888                                 Err(io::Error::new(io::ErrorKind::InvalidData, "cannot parse u64 from update name"))
889                         }
890                 }
891         }
892
893         /// Convert this monitor update name to a &str
894         pub fn as_str(&self) -> &str {
895                 &self.1
896         }
897 }
898
899 impl From<u64> for UpdateName {
900         fn from(value: u64) -> Self {
901                 Self(value, value.to_string())
902         }
903 }
904
905 #[cfg(test)]
906 mod tests {
907         use super::*;
908         use crate::chain::chainmonitor::Persist;
909         use crate::chain::ChannelMonitorUpdateStatus;
910         use crate::events::{ClosureReason, MessageSendEventsProvider};
911         use crate::ln::functional_test_utils::*;
912         use crate::util::test_utils::{self, TestLogger, TestStore};
913         use crate::{check_added_monitors, check_closed_broadcast};
914
915         const EXPECTED_UPDATES_PER_PAYMENT: u64 = 5;
916
917         #[test]
918         fn converts_u64_to_update_name() {
919                 assert_eq!(UpdateName::from(0).as_str(), "0");
920                 assert_eq!(UpdateName::from(21).as_str(), "21");
921                 assert_eq!(UpdateName::from(u64::MAX).as_str(), "18446744073709551615");
922         }
923
924         #[test]
925         fn bad_update_name_fails() {
926                 assert!(UpdateName::new("deadbeef".to_string()).is_err());
927                 assert!(UpdateName::new("-1".to_string()).is_err());
928         }
929
930         #[test]
931         fn monitor_from_outpoint_works() {
932                 let monitor_name1 = MonitorName::from(OutPoint {
933                         txid: Txid::from_str("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef").unwrap(),
934                         index: 1,
935                 });
936                 assert_eq!(monitor_name1.as_str(), "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_1");
937
938                 let monitor_name2 = MonitorName::from(OutPoint {
939                         txid: Txid::from_str("f33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeef").unwrap(),
940                         index: u16::MAX,
941                 });
942                 assert_eq!(monitor_name2.as_str(), "f33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeeff33dbeef_65535");
943         }
944
945         #[test]
946         fn bad_monitor_string_fails() {
947                 assert!(MonitorName::new("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef".to_string()).is_err());
948                 assert!(MonitorName::new("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_65536".to_string()).is_err());
949                 assert!(MonitorName::new("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef_21".to_string()).is_err());
950         }
951
952         // Exercise the `MonitorUpdatingPersister` with real channels and payments.
953         #[test]
954         fn persister_with_real_monitors() {
955                 // This value is used later to limit how many iterations we perform.
956                 let persister_0_max_pending_updates = 7;
957                 // Intentionally set this to a smaller value to test a different alignment.
958                 let persister_1_max_pending_updates = 3;
959                 let chanmon_cfgs = create_chanmon_cfgs(4);
960                 let persister_0 = MonitorUpdatingPersister {
961                         kv_store: &TestStore::new(false),
962                         logger: &TestLogger::new(),
963                         maximum_pending_updates: persister_0_max_pending_updates,
964                         entropy_source: &chanmon_cfgs[0].keys_manager,
965                         signer_provider: &chanmon_cfgs[0].keys_manager,
966                 };
967                 let persister_1 = MonitorUpdatingPersister {
968                         kv_store: &TestStore::new(false),
969                         logger: &TestLogger::new(),
970                         maximum_pending_updates: persister_1_max_pending_updates,
971                         entropy_source: &chanmon_cfgs[1].keys_manager,
972                         signer_provider: &chanmon_cfgs[1].keys_manager,
973                 };
974                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
975                 let chain_mon_0 = test_utils::TestChainMonitor::new(
976                         Some(&chanmon_cfgs[0].chain_source),
977                         &chanmon_cfgs[0].tx_broadcaster,
978                         &chanmon_cfgs[0].logger,
979                         &chanmon_cfgs[0].fee_estimator,
980                         &persister_0,
981                         &chanmon_cfgs[0].keys_manager,
982                 );
983                 let chain_mon_1 = test_utils::TestChainMonitor::new(
984                         Some(&chanmon_cfgs[1].chain_source),
985                         &chanmon_cfgs[1].tx_broadcaster,
986                         &chanmon_cfgs[1].logger,
987                         &chanmon_cfgs[1].fee_estimator,
988                         &persister_1,
989                         &chanmon_cfgs[1].keys_manager,
990                 );
991                 node_cfgs[0].chain_monitor = chain_mon_0;
992                 node_cfgs[1].chain_monitor = chain_mon_1;
993                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
994                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
995                 let broadcaster_0 = &chanmon_cfgs[2].tx_broadcaster;
996                 let broadcaster_1 = &chanmon_cfgs[3].tx_broadcaster;
997
998                 // Check that the persisted channel data is empty before any channels are
999                 // open.
1000                 let mut persisted_chan_data_0 = persister_0.read_all_channel_monitors_with_updates(
1001                         &broadcaster_0, &&chanmon_cfgs[0].fee_estimator).unwrap();
1002                 assert_eq!(persisted_chan_data_0.len(), 0);
1003                 let mut persisted_chan_data_1 = persister_1.read_all_channel_monitors_with_updates(
1004                         &broadcaster_1, &&chanmon_cfgs[1].fee_estimator).unwrap();
1005                 assert_eq!(persisted_chan_data_1.len(), 0);
1006
1007                 // Helper to make sure the channel is on the expected update ID.
1008                 macro_rules! check_persisted_data {
1009                         ($expected_update_id: expr) => {
1010                                 persisted_chan_data_0 = persister_0.read_all_channel_monitors_with_updates(
1011                                         &broadcaster_0, &&chanmon_cfgs[0].fee_estimator).unwrap();
1012                                 // check that we stored only one monitor
1013                                 assert_eq!(persisted_chan_data_0.len(), 1);
1014                                 for (_, mon) in persisted_chan_data_0.iter() {
1015                                         // check that when we read it, we got the right update id
1016                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
1017
1018                                         // if the CM is at consolidation threshold, ensure no updates are stored.
1019                                         let monitor_name = MonitorName::from(mon.get_funding_txo().0);
1020                                         if mon.get_latest_update_id() % persister_0_max_pending_updates == 0
1021                                                         || mon.get_latest_update_id() == CLOSED_CHANNEL_UPDATE_ID {
1022                                                 assert_eq!(
1023                                                         persister_0.kv_store.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
1024                                                                 monitor_name.as_str()).unwrap().len(),
1025                                                         0,
1026                                                         "updates stored when they shouldn't be in persister 0"
1027                                                 );
1028                                         }
1029                                 }
1030                                 persisted_chan_data_1 = persister_1.read_all_channel_monitors_with_updates(
1031                                         &broadcaster_1, &&chanmon_cfgs[1].fee_estimator).unwrap();
1032                                 assert_eq!(persisted_chan_data_1.len(), 1);
1033                                 for (_, mon) in persisted_chan_data_1.iter() {
1034                                         assert_eq!(mon.get_latest_update_id(), $expected_update_id);
1035                                         let monitor_name = MonitorName::from(mon.get_funding_txo().0);
1036                                         // if the CM is at consolidation threshold, ensure no updates are stored.
1037                                         if mon.get_latest_update_id() % persister_1_max_pending_updates == 0
1038                                                         || mon.get_latest_update_id() == CLOSED_CHANNEL_UPDATE_ID {
1039                                                 assert_eq!(
1040                                                         persister_1.kv_store.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE,
1041                                                                 monitor_name.as_str()).unwrap().len(),
1042                                                         0,
1043                                                         "updates stored when they shouldn't be in persister 1"
1044                                                 );
1045                                         }
1046                                 }
1047                         };
1048                 }
1049
1050                 // Create some initial channel and check that a channel was persisted.
1051                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
1052                 check_persisted_data!(0);
1053
1054                 // Send a few payments and make sure the monitors are updated to the latest.
1055                 send_payment(&nodes[0], &vec![&nodes[1]][..], 8_000_000);
1056                 check_persisted_data!(EXPECTED_UPDATES_PER_PAYMENT);
1057                 send_payment(&nodes[1], &vec![&nodes[0]][..], 4_000_000);
1058                 check_persisted_data!(2 * EXPECTED_UPDATES_PER_PAYMENT);
1059
1060                 // Send a few more payments to try all the alignments of max pending updates with
1061                 // updates for a payment sent and received.
1062                 let mut sender = 0;
1063                 for i in 3..=persister_0_max_pending_updates * 2 {
1064                         let receiver;
1065                         if sender == 0 {
1066                                 sender = 1;
1067                                 receiver = 0;
1068                         } else {
1069                                 sender = 0;
1070                                 receiver = 1;
1071                         }
1072                         send_payment(&nodes[sender], &vec![&nodes[receiver]][..], 21_000);
1073                         check_persisted_data!(i * EXPECTED_UPDATES_PER_PAYMENT);
1074                 }
1075
1076                 // Force close because cooperative close doesn't result in any persisted
1077                 // updates.
1078                 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1079
1080                 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
1081                 check_closed_broadcast!(nodes[0], true);
1082                 check_added_monitors!(nodes[0], 1);
1083
1084                 let node_txn = nodes[0].tx_broadcaster.txn_broadcast();
1085                 assert_eq!(node_txn.len(), 1);
1086
1087                 connect_block(&nodes[1], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_txn[0].clone(), node_txn[0].clone()]));
1088
1089                 check_closed_broadcast!(nodes[1], true);
1090                 check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false, &[nodes[0].node.get_our_node_id()], 100000);
1091                 check_added_monitors!(nodes[1], 1);
1092
1093                 // Make sure everything is persisted as expected after close.
1094                 check_persisted_data!(CLOSED_CHANNEL_UPDATE_ID);
1095
1096                 // Make sure the expected number of stale updates is present.
1097                 let persisted_chan_data = persister_0.read_all_channel_monitors_with_updates(&broadcaster_0, &&chanmon_cfgs[0].fee_estimator).unwrap();
1098                 let (_, monitor) = &persisted_chan_data[0];
1099                 let monitor_name = MonitorName::from(monitor.get_funding_txo().0);
1100                 // The channel should have 0 updates, as it wrote a full monitor and consolidated.
1101                 assert_eq!(persister_0.kv_store.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str()).unwrap().len(), 0);
1102                 assert_eq!(persister_1.kv_store.list(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str()).unwrap().len(), 0);
1103         }
1104
1105         // Test that if the `MonitorUpdatingPersister`'s can't actually write, trying to persist a
1106         // monitor or update with it results in the persister returning an UnrecoverableError status.
1107         #[test]
1108         fn unrecoverable_error_on_write_failure() {
1109                 // Set up a dummy channel and force close. This will produce a monitor
1110                 // that we can then use to test persistence.
1111                 let chanmon_cfgs = create_chanmon_cfgs(2);
1112                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1113                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1114                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1115                 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
1116                 nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
1117                 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
1118                 {
1119                         let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1120                         let update_map = nodes[1].chain_monitor.latest_monitor_update_id.lock().unwrap();
1121                         let update_id = update_map.get(&added_monitors[0].1.channel_id()).unwrap();
1122                         let cmu_map = nodes[1].chain_monitor.monitor_updates.lock().unwrap();
1123                         let cmu = &cmu_map.get(&added_monitors[0].1.channel_id()).unwrap()[0];
1124                         let test_txo = OutPoint { txid: Txid::from_str("8984484a580b825b9972d7adb15050b3ab624ccd731946b3eeddb92f4e7ef6be").unwrap(), index: 0 };
1125
1126                         let ro_persister = MonitorUpdatingPersister {
1127                                 kv_store: &TestStore::new(true),
1128                                 logger: &TestLogger::new(),
1129                                 maximum_pending_updates: 11,
1130                                 entropy_source: node_cfgs[0].keys_manager,
1131                                 signer_provider: node_cfgs[0].keys_manager,
1132                         };
1133                         match ro_persister.persist_new_channel(test_txo, &added_monitors[0].1, update_id.2) {
1134                                 ChannelMonitorUpdateStatus::UnrecoverableError => {
1135                                         // correct result
1136                                 }
1137                                 ChannelMonitorUpdateStatus::Completed => {
1138                                         panic!("Completed persisting new channel when shouldn't have")
1139                                 }
1140                                 ChannelMonitorUpdateStatus::InProgress => {
1141                                         panic!("Returned InProgress when shouldn't have")
1142                                 }
1143                         }
1144                         match ro_persister.update_persisted_channel(test_txo, Some(cmu), &added_monitors[0].1, update_id.2) {
1145                                 ChannelMonitorUpdateStatus::UnrecoverableError => {
1146                                         // correct result
1147                                 }
1148                                 ChannelMonitorUpdateStatus::Completed => {
1149                                         panic!("Completed persisting new channel when shouldn't have")
1150                                 }
1151                                 ChannelMonitorUpdateStatus::InProgress => {
1152                                         panic!("Returned InProgress when shouldn't have")
1153                                 }
1154                         }
1155                         added_monitors.clear();
1156                 }
1157                 nodes[1].node.get_and_clear_pending_msg_events();
1158         }
1159
1160         // Confirm that the `clean_stale_updates` function finds and deletes stale updates.
1161         #[test]
1162         fn clean_stale_updates_works() {
1163                 let test_max_pending_updates = 7;
1164                 let chanmon_cfgs = create_chanmon_cfgs(3);
1165                 let persister_0 = MonitorUpdatingPersister {
1166                         kv_store: &TestStore::new(false),
1167                         logger: &TestLogger::new(),
1168                         maximum_pending_updates: test_max_pending_updates,
1169                         entropy_source: &chanmon_cfgs[0].keys_manager,
1170                         signer_provider: &chanmon_cfgs[0].keys_manager,
1171                 };
1172                 let persister_1 = MonitorUpdatingPersister {
1173                         kv_store: &TestStore::new(false),
1174                         logger: &TestLogger::new(),
1175                         maximum_pending_updates: test_max_pending_updates,
1176                         entropy_source: &chanmon_cfgs[1].keys_manager,
1177                         signer_provider: &chanmon_cfgs[1].keys_manager,
1178                 };
1179                 let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1180                 let chain_mon_0 = test_utils::TestChainMonitor::new(
1181                         Some(&chanmon_cfgs[0].chain_source),
1182                         &chanmon_cfgs[0].tx_broadcaster,
1183                         &chanmon_cfgs[0].logger,
1184                         &chanmon_cfgs[0].fee_estimator,
1185                         &persister_0,
1186                         &chanmon_cfgs[0].keys_manager,
1187                 );
1188                 let chain_mon_1 = test_utils::TestChainMonitor::new(
1189                         Some(&chanmon_cfgs[1].chain_source),
1190                         &chanmon_cfgs[1].tx_broadcaster,
1191                         &chanmon_cfgs[1].logger,
1192                         &chanmon_cfgs[1].fee_estimator,
1193                         &persister_1,
1194                         &chanmon_cfgs[1].keys_manager,
1195                 );
1196                 node_cfgs[0].chain_monitor = chain_mon_0;
1197                 node_cfgs[1].chain_monitor = chain_mon_1;
1198                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1199                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1200
1201                 let broadcaster_0 = &chanmon_cfgs[2].tx_broadcaster;
1202
1203                 // Check that the persisted channel data is empty before any channels are
1204                 // open.
1205                 let persisted_chan_data = persister_0.read_all_channel_monitors_with_updates(&broadcaster_0, &&chanmon_cfgs[0].fee_estimator).unwrap();
1206                 assert_eq!(persisted_chan_data.len(), 0);
1207
1208                 // Create some initial channel
1209                 let _ = create_announced_chan_between_nodes(&nodes, 0, 1);
1210
1211                 // Send a few payments to advance the updates a bit
1212                 send_payment(&nodes[0], &vec![&nodes[1]][..], 8_000_000);
1213                 send_payment(&nodes[1], &vec![&nodes[0]][..], 4_000_000);
1214
1215                 // Get the monitor and make a fake stale update at update_id=1 (lowest height of an update possible)
1216                 let persisted_chan_data = persister_0.read_all_channel_monitors_with_updates(&broadcaster_0, &&chanmon_cfgs[0].fee_estimator).unwrap();
1217                 let (_, monitor) = &persisted_chan_data[0];
1218                 let monitor_name = MonitorName::from(monitor.get_funding_txo().0);
1219                 persister_0
1220                         .kv_store
1221                         .write(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str(), UpdateName::from(1).as_str(), &[0u8; 1])
1222                         .unwrap();
1223
1224                 // Do the stale update cleanup
1225                 persister_0.cleanup_stale_updates(false).unwrap();
1226
1227                 // Confirm the stale update is unreadable/gone
1228                 assert!(persister_0
1229                         .kv_store
1230                         .read(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str(), UpdateName::from(1).as_str())
1231                         .is_err());
1232
1233                 // Force close.
1234                 nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
1235                 check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
1236                 check_closed_broadcast!(nodes[0], true);
1237                 check_added_monitors!(nodes[0], 1);
1238
1239                 // Write an update near u64::MAX
1240                 persister_0
1241                         .kv_store
1242                         .write(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str(), UpdateName::from(u64::MAX - 1).as_str(), &[0u8; 1])
1243                         .unwrap();
1244
1245                 // Do the stale update cleanup
1246                 persister_0.cleanup_stale_updates(false).unwrap();
1247
1248                 // Confirm the stale update is unreadable/gone
1249                 assert!(persister_0
1250                         .kv_store
1251                         .read(CHANNEL_MONITOR_UPDATE_PERSISTENCE_PRIMARY_NAMESPACE, monitor_name.as_str(), UpdateName::from(u64::MAX - 1).as_str())
1252                         .is_err());
1253         }
1254 }