Merge pull request #2176 from TheBlueMatt/2023-04-expose-success-prob
[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::ops::Deref;
12 use bitcoin::hashes::hex::{FromHex, ToHex};
13 use bitcoin::{BlockHash, Txid};
14
15 use crate::io;
16 use crate::prelude::{Vec, String};
17 use crate::routing::scoring::WriteableScore;
18
19 use crate::chain;
20 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
21 use crate::chain::chainmonitor::{Persist, MonitorUpdateId};
22 use crate::sign::{EntropySource, NodeSigner, WriteableEcdsaChannelSigner, SignerProvider};
23 use crate::chain::transaction::OutPoint;
24 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate};
25 use crate::ln::channelmanager::ChannelManager;
26 use crate::routing::router::Router;
27 use crate::routing::gossip::NetworkGraph;
28 use crate::util::logger::Logger;
29 use crate::util::ser::{ReadableArgs, Writeable};
30
31 /// The alphabet of characters allowed for namespaces and keys.
32 pub const KVSTORE_NAMESPACE_KEY_ALPHABET: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
33
34 /// The maximum number of characters namespaces and keys may have.
35 pub const KVSTORE_NAMESPACE_KEY_MAX_LEN: usize = 120;
36
37 /// The namespace under which the [`ChannelManager`] will be persisted.
38 pub const CHANNEL_MANAGER_PERSISTENCE_NAMESPACE: &str = "";
39 /// The sub-namespace under which the [`ChannelManager`] will be persisted.
40 pub const CHANNEL_MANAGER_PERSISTENCE_SUB_NAMESPACE: &str = "";
41 /// The key under which the [`ChannelManager`] will be persisted.
42 pub const CHANNEL_MANAGER_PERSISTENCE_KEY: &str = "manager";
43
44 /// The namespace under which [`ChannelMonitor`]s will be persisted.
45 pub const CHANNEL_MONITOR_PERSISTENCE_NAMESPACE: &str = "monitors";
46 /// The sub-namespace under which [`ChannelMonitor`]s will be persisted.
47 pub const CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE: &str = "";
48
49 /// The namespace under which the [`NetworkGraph`] will be persisted.
50 pub const NETWORK_GRAPH_PERSISTENCE_NAMESPACE: &str = "";
51 /// The sub-namespace under which the [`NetworkGraph`] will be persisted.
52 pub const NETWORK_GRAPH_PERSISTENCE_SUB_NAMESPACE: &str = "";
53 /// The key under which the [`NetworkGraph`] will be persisted.
54 pub const NETWORK_GRAPH_PERSISTENCE_KEY: &str = "network_graph";
55
56 /// The namespace under which the [`WriteableScore`] will be persisted.
57 pub const SCORER_PERSISTENCE_NAMESPACE: &str = "";
58 /// The sub-namespace under which the [`WriteableScore`] will be persisted.
59 pub const SCORER_PERSISTENCE_SUB_NAMESPACE: &str = "";
60 /// The key under which the [`WriteableScore`] will be persisted.
61 pub const SCORER_PERSISTENCE_KEY: &str = "scorer";
62
63 /// Provides an interface that allows storage and retrieval of persisted values that are associated
64 /// with given keys.
65 ///
66 /// In order to avoid collisions the key space is segmented based on the given `namespace`s and
67 /// `sub_namespace`s. Implementations of this trait are free to handle them in different ways, as
68 /// long as per-namespace key uniqueness is asserted.
69 ///
70 /// Keys and namespaces are required to be valid ASCII strings in the range of
71 /// [`KVSTORE_NAMESPACE_KEY_ALPHABET`] and no longer than [`KVSTORE_NAMESPACE_KEY_MAX_LEN`]. Empty
72 /// namespaces and sub-namespaces (`""`) are assumed to be a valid, however, if `namespace` is
73 /// empty, `sub_namespace` is required to be empty, too. This means that concerns should always be
74 /// separated by namespace first, before sub-namespaces are used. While the number of namespaces
75 /// will be relatively small and is determined at compile time, there may be many sub-namespaces
76 /// per namespace. Note that per-namespace uniqueness needs to also hold for keys *and*
77 /// namespaces/sub-namespaces in any given namespace/sub-namespace, i.e., conflicts between keys
78 /// and equally named namespaces/sub-namespaces must be avoided.
79 ///
80 /// **Note:** Users migrating custom persistence backends from the pre-v0.0.117 `KVStorePersister`
81 /// interface can use a concatenation of `[{namespace}/[{sub_namespace}/]]{key}` to recover a `key` compatible with the
82 /// data model previously assumed by `KVStorePersister::persist`.
83 pub trait KVStore {
84         /// Returns the data stored for the given `namespace`, `sub_namespace`, and `key`.
85         ///
86         /// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given
87         /// `namespace` and `sub_namespace`.
88         ///
89         /// [`ErrorKind::NotFound`]: io::ErrorKind::NotFound
90         fn read(&self, namespace: &str, sub_namespace: &str, key: &str) -> io::Result<Vec<u8>>;
91         /// Persists the given data under the given `key`.
92         ///
93         /// Will create the given `namespace` and `sub_namespace` if not already present in the store.
94         fn write(&self, namespace: &str, sub_namespace: &str, key: &str, buf: &[u8]) -> io::Result<()>;
95         /// Removes any data that had previously been persisted under the given `key`.
96         ///
97         /// If the `lazy` flag is set to `true`, the backend implementation might choose to lazily
98         /// remove the given `key` at some point in time after the method returns, e.g., as part of an
99         /// eventual batch deletion of multiple keys. As a consequence, subsequent calls to
100         /// [`KVStore::list`] might include the removed key until the changes are actually persisted.
101         ///
102         /// Note that while setting the `lazy` flag reduces the I/O burden of multiple subsequent
103         /// `remove` calls, it also influences the atomicity guarantees as lazy `remove`s could
104         /// potentially get lost on crash after the method returns. Therefore, this flag should only be
105         /// set for `remove` operations that can be safely replayed at a later time.
106         ///
107         /// Returns successfully if no data will be stored for the given `namespace`, `sub_namespace`, and
108         /// `key`, independently of whether it was present before its invokation or not.
109         fn remove(&self, namespace: &str, sub_namespace: &str, key: &str, lazy: bool) -> io::Result<()>;
110         /// Returns a list of keys that are stored under the given `sub_namespace` in `namespace`.
111         ///
112         /// Returns the keys in arbitrary order, so users requiring a particular order need to sort the
113         /// returned keys. Returns an empty list if `namespace` or `sub_namespace` is unknown.
114         fn list(&self, namespace: &str, sub_namespace: &str) -> io::Result<Vec<String>>;
115 }
116
117 /// Trait that handles persisting a [`ChannelManager`], [`NetworkGraph`], and [`WriteableScore`] to disk.
118 pub trait Persister<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>>
119         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
120                 T::Target: 'static + BroadcasterInterface,
121                 ES::Target: 'static + EntropySource,
122                 NS::Target: 'static + NodeSigner,
123                 SP::Target: 'static + SignerProvider,
124                 F::Target: 'static + FeeEstimator,
125                 R::Target: 'static + Router,
126                 L::Target: 'static + Logger,
127 {
128         /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed.
129         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error>;
130
131         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
132         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error>;
133
134         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
135         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error>;
136 }
137
138
139 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
140         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
141                 T::Target: 'static + BroadcasterInterface,
142                 ES::Target: 'static + EntropySource,
143                 NS::Target: 'static + NodeSigner,
144                 SP::Target: 'static + SignerProvider,
145                 F::Target: 'static + FeeEstimator,
146                 R::Target: 'static + Router,
147                 L::Target: 'static + Logger,
148 {
149         /// Persist the given [`ChannelManager`] to disk, returning an error if persistence failed.
150         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error> {
151                 self.write(CHANNEL_MANAGER_PERSISTENCE_NAMESPACE,
152                                    CHANNEL_MANAGER_PERSISTENCE_SUB_NAMESPACE,
153                                    CHANNEL_MANAGER_PERSISTENCE_KEY,
154                                    &channel_manager.encode())
155         }
156
157         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
158         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error> {
159                 self.write(NETWORK_GRAPH_PERSISTENCE_NAMESPACE,
160                                    NETWORK_GRAPH_PERSISTENCE_SUB_NAMESPACE,
161                                    NETWORK_GRAPH_PERSISTENCE_KEY,
162                                    &network_graph.encode())
163         }
164
165         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
166         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error> {
167                 self.write(SCORER_PERSISTENCE_NAMESPACE,
168                                    SCORER_PERSISTENCE_SUB_NAMESPACE,
169                                    SCORER_PERSISTENCE_KEY,
170                                    &scorer.encode())
171         }
172 }
173
174 impl<ChannelSigner: WriteableEcdsaChannelSigner, K: KVStore> Persist<ChannelSigner> for K {
175         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
176         // down once these start returning failure.
177         // A PermanentFailure implies we should probably just shut down the node since we're
178         // force-closing channels without even broadcasting!
179
180         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
181                 let key = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
182                 match self.write(
183                         CHANNEL_MONITOR_PERSISTENCE_NAMESPACE,
184                         CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE,
185                         &key, &monitor.encode())
186                 {
187                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
188                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
189                 }
190         }
191
192         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
193                 let key = format!("{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
194                 match self.write(
195                         CHANNEL_MONITOR_PERSISTENCE_NAMESPACE,
196                         CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE,
197                         &key, &monitor.encode())
198                 {
199                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
200                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
201                 }
202         }
203 }
204
205 /// Read previously persisted [`ChannelMonitor`]s from the store.
206 pub fn read_channel_monitors<K: Deref, ES: Deref, SP: Deref>(
207         kv_store: K, entropy_source: ES, signer_provider: SP,
208 ) -> io::Result<Vec<(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::Signer>)>>
209 where
210         K::Target: KVStore,
211         ES::Target: EntropySource + Sized,
212         SP::Target: SignerProvider + Sized,
213 {
214         let mut res = Vec::new();
215
216         for stored_key in kv_store.list(
217                 CHANNEL_MONITOR_PERSISTENCE_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE)?
218         {
219                 if stored_key.len() < 66 {
220                         return Err(io::Error::new(
221                                 io::ErrorKind::InvalidData,
222                                 "Stored key has invalid length"));
223                 }
224
225                 let txid = Txid::from_hex(stored_key.split_at(64).0).map_err(|_| {
226                         io::Error::new(io::ErrorKind::InvalidData, "Invalid tx ID in stored key")
227                 })?;
228
229                 let index: u16 = stored_key.split_at(65).1.parse().map_err(|_| {
230                         io::Error::new(io::ErrorKind::InvalidData, "Invalid tx index in stored key")
231                 })?;
232
233                 match <(BlockHash, ChannelMonitor<<SP::Target as SignerProvider>::Signer>)>::read(
234                         &mut io::Cursor::new(
235                                 kv_store.read(CHANNEL_MONITOR_PERSISTENCE_NAMESPACE, CHANNEL_MONITOR_PERSISTENCE_SUB_NAMESPACE, &stored_key)?),
236                         (&*entropy_source, &*signer_provider),
237                 ) {
238                         Ok((block_hash, channel_monitor)) => {
239                                 if channel_monitor.get_funding_txo().0.txid != txid
240                                         || channel_monitor.get_funding_txo().0.index != index
241                                 {
242                                         return Err(io::Error::new(
243                                                 io::ErrorKind::InvalidData,
244                                                 "ChannelMonitor was stored under the wrong key",
245                                         ));
246                                 }
247                                 res.push((block_hash, channel_monitor));
248                         }
249                         Err(_) => {
250                                 return Err(io::Error::new(
251                                         io::ErrorKind::InvalidData,
252                                         "Failed to deserialize ChannelMonitor"
253                                 ))
254                         }
255                 }
256         }
257         Ok(res)
258 }