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
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.
12 use bitcoin::hashes::hex::ToHex;
14 use crate::prelude::{Vec, String};
15 use crate::routing::scoring::WriteableScore;
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;
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";
34 /// The namespace under which [`ChannelMonitor`]s will be persisted.
35 pub const CHANNEL_MONITOR_PERSISTENCE_NAMESPACE: &str = "monitors";
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";
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";
47 /// Provides an interface that allows to store and retrieve persisted values that are associated
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.
54 /// Keys and namespaces are required to be valid ASCII strings and the empty namespace (`""`) is
55 /// assumed to be valid namespace.
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
62 /// Returns an [`ErrorKind::NotFound`] if the given `key` could not be found in the given `namespace`.
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`.
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`.
75 /// Will return an empty list if the `namespace` is unknown.
76 fn list(&self, namespace: &str) -> io::Result<Vec<String>>;
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<()>;
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,
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>;
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>;
105 /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
106 fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error>;
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,
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)
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)
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)
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!
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,
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,