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