Add `KVStore` interface trait
[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 KVStorePersister 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::ToHex;
13 use crate::io;
14 use crate::prelude::{Vec, String};
15 use crate::routing::scoring::WriteableScore;
16
17 use crate::chain;
18 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
19 use crate::chain::chainmonitor::{Persist, MonitorUpdateId};
20 use crate::sign::{EntropySource, NodeSigner, WriteableEcdsaChannelSigner, SignerProvider};
21 use crate::chain::transaction::OutPoint;
22 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate};
23 use crate::ln::channelmanager::ChannelManager;
24 use crate::routing::router::Router;
25 use crate::routing::gossip::NetworkGraph;
26 use crate::util::logger::Logger;
27 use crate::util::ser::Writeable;
28
29 /// The namespace under which the [`ChannelManager`] will be persisted.
30 pub const CHANNEL_MANAGER_PERSISTENCE_NAMESPACE: &str = "";
31 /// The key under which the [`ChannelManager`] will be persisted.
32 pub const CHANNEL_MANAGER_PERSISTENCE_KEY: &str = "manager";
33
34 /// The namespace under which [`ChannelMonitor`]s will be persisted.
35 pub const CHANNEL_MONITOR_PERSISTENCE_NAMESPACE: &str = "monitors";
36
37 /// The namespace under which the [`NetworkGraph`] will be persisted.
38 pub const NETWORK_GRAPH_PERSISTENCE_NAMESPACE: &str = "";
39 /// The key under which the [`NetworkGraph`] will be persisted.
40 pub const NETWORK_GRAPH_PERSISTENCE_KEY: &str = "network_graph";
41
42 /// The namespace under which the [`WriteableScore`] will be persisted.
43 pub const SCORER_PERSISTENCE_NAMESPACE: &str = "";
44 /// The key under which the [`WriteableScore`] will be persisted.
45 pub const SCORER_PERSISTENCE_KEY: &str = "scorer";
46
47 /// Provides an interface that allows to store and retrieve persisted values that are associated
48 /// with given keys.
49 ///
50 /// In order to avoid collisions the key space is segmented based on the given `namespace`s.
51 /// Implementations of this trait are free to handle them in different ways, as long as
52 /// per-namespace key uniqueness is asserted.
53 ///
54 /// Keys and namespaces are required to be valid ASCII strings and the empty namespace (`""`) is
55 /// assumed to be valid namespace.
56 pub trait KVStore {
57         /// A reader as returned by [`Self::read`].
58         type Reader: io::Read;
59         /// Returns an [`io::Read`] for the given `namespace` and `key` from which [`Readable`]s may be
60         /// read.
61         ///
62         /// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given `namespace`.
63         ///
64         /// [`Readable`]: crate::util::ser::Readable
65         /// [`ErrorKind::NotFound`]: io::ErrorKind::NotFound
66         fn read(&self, namespace: &str, key: &str) -> io::Result<Self::Reader>;
67         /// Persists the given data under the given `key`.
68         ///
69         /// Will create the given `namespace` if not already present in the store.
70         fn write(&self, namespace: &str, key: &str, buf: &[u8]) -> io::Result<()>;
71         /// Removes any data that had previously been persisted under the given `key`.
72         fn remove(&self, namespace: &str, key: &str) -> io::Result<()>;
73         /// Returns a list of keys that are stored under the given `namespace`.
74         ///
75         /// Will return an empty list if the `namespace` is unknown.
76         fn list(&self, namespace: &str) -> io::Result<Vec<String>>;
77 }
78
79 /// Trait for a key-value store for persisting some writeable object at some key
80 /// Implementing `KVStorePersister` provides auto-implementations for [`Persister`]
81 /// and [`Persist`] traits.  It uses "manager", "network_graph",
82 /// and "monitors/{funding_txo_id}_{funding_txo_index}" for keys.
83 pub trait KVStorePersister {
84         /// Persist the given writeable using the provided key
85         fn persist<W: Writeable>(&self, key: &str, object: &W) -> io::Result<()>;
86 }
87
88 /// Trait that handles persisting a [`ChannelManager`], [`NetworkGraph`], and [`WriteableScore`] to disk.
89 pub trait Persister<'a, M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>>
90         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
91                 T::Target: 'static + BroadcasterInterface,
92                 ES::Target: 'static + EntropySource,
93                 NS::Target: 'static + NodeSigner,
94                 SP::Target: 'static + SignerProvider,
95                 F::Target: 'static + FeeEstimator,
96                 R::Target: 'static + Router,
97                 L::Target: 'static + Logger,
98 {
99         /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed.
100         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error>;
101
102         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
103         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error>;
104
105         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
106         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error>;
107 }
108
109 impl<'a, A: KVStorePersister, 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
110         where M::Target: 'static + chain::Watch<<SP::Target as SignerProvider>::Signer>,
111                 T::Target: 'static + BroadcasterInterface,
112                 ES::Target: 'static + EntropySource,
113                 NS::Target: 'static + NodeSigner,
114                 SP::Target: 'static + SignerProvider,
115                 F::Target: 'static + FeeEstimator,
116                 R::Target: 'static + Router,
117                 L::Target: 'static + Logger,
118 {
119         /// Persist the given ['ChannelManager'] to disk with the name "manager", returning an error if persistence failed.
120         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, ES, NS, SP, F, R, L>) -> Result<(), io::Error> {
121                 self.persist("manager", channel_manager)
122         }
123
124         /// Persist the given [`NetworkGraph`] to disk with the name "network_graph", returning an error if persistence failed.
125         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error> {
126                 self.persist("network_graph", network_graph)
127         }
128
129         /// Persist the given [`WriteableScore`] to disk with name "scorer", returning an error if persistence failed.
130         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error> {
131                 self.persist("scorer", &scorer)
132         }
133 }
134
135 impl<ChannelSigner: WriteableEcdsaChannelSigner, K: KVStorePersister> Persist<ChannelSigner> for K {
136         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
137         // down once these start returning failure.
138         // A PermanentFailure implies we should probably just shut down the node since we're
139         // force-closing channels without even broadcasting!
140
141         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
142                 let key = format!("monitors/{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
143                 match self.persist(&key, monitor) {
144                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
145                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
146                 }
147         }
148
149         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: Option<&ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
150                 let key = format!("monitors/{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
151                 match self.persist(&key, monitor) {
152                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
153                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
154                 }
155         }
156 }