Merge pull request #1823 from mariocynicys/expose-tlv-macros2
[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::routing::scoring::WriteableScore;
15
16 use crate::chain;
17 use crate::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
18 use crate::chain::chainmonitor::{Persist, MonitorUpdateId};
19 use crate::chain::keysinterface::{Sign, KeysInterface, SignerProvider};
20 use crate::chain::transaction::OutPoint;
21 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate};
22 use crate::ln::channelmanager::ChannelManager;
23 use crate::routing::router::Router;
24 use crate::routing::gossip::NetworkGraph;
25 use super::{logger::Logger, ser::Writeable};
26
27 /// Trait for a key-value store for persisting some writeable object at some key
28 /// Implementing `KVStorePersister` provides auto-implementations for [`Persister`]
29 /// and [`Persist`] traits.  It uses "manager", "network_graph",
30 /// and "monitors/{funding_txo_id}_{funding_txo_index}" for keys.
31 pub trait KVStorePersister {
32         /// Persist the given writeable using the provided key
33         fn persist<W: Writeable>(&self, key: &str, object: &W) -> io::Result<()>;
34 }
35
36 /// Trait that handles persisting a [`ChannelManager`], [`NetworkGraph`], and [`WriteableScore`] to disk.
37 pub trait Persister<'a, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>>
38         where M::Target: 'static + chain::Watch<<K::Target as SignerProvider>::Signer>,
39                 T::Target: 'static + BroadcasterInterface,
40                 K::Target: 'static + KeysInterface,
41                 F::Target: 'static + FeeEstimator,
42                 R::Target: 'static + Router,
43                 L::Target: 'static + Logger,
44 {
45         /// Persist the given ['ChannelManager'] to disk, returning an error if persistence failed.
46         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, K, F, R, L>) -> Result<(), io::Error>;
47
48         /// Persist the given [`NetworkGraph`] to disk, returning an error if persistence failed.
49         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error>;
50
51         /// Persist the given [`WriteableScore`] to disk, returning an error if persistence failed.
52         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error>;
53 }
54
55 impl<'a, A: KVStorePersister, M: Deref, T: Deref, K: Deref, F: Deref, R: Deref, L: Deref, S: WriteableScore<'a>> Persister<'a, M, T, K, F, R, L, S> for A
56         where M::Target: 'static + chain::Watch<<K::Target as SignerProvider>::Signer>,
57                 T::Target: 'static + BroadcasterInterface,
58                 K::Target: 'static + KeysInterface,
59                 F::Target: 'static + FeeEstimator,
60                 R::Target: 'static + Router,
61                 L::Target: 'static + Logger,
62 {
63         /// Persist the given ['ChannelManager'] to disk with the name "manager", returning an error if persistence failed.
64         fn persist_manager(&self, channel_manager: &ChannelManager<M, T, K, F, R, L>) -> Result<(), io::Error> {
65                 self.persist("manager", channel_manager)
66         }
67
68         /// Persist the given [`NetworkGraph`] to disk with the name "network_graph", returning an error if persistence failed.
69         fn persist_graph(&self, network_graph: &NetworkGraph<L>) -> Result<(), io::Error> {
70                 self.persist("network_graph", network_graph)
71         }
72
73         /// Persist the given [`WriteableScore`] to disk with name "scorer", returning an error if persistence failed.
74         fn persist_scorer(&self, scorer: &S) -> Result<(), io::Error> {
75                 self.persist("scorer", &scorer)
76         }
77 }
78
79 impl<ChannelSigner: Sign, K: KVStorePersister> Persist<ChannelSigner> for K {
80         // TODO: We really need a way for the persister to inform the user that its time to crash/shut
81         // down once these start returning failure.
82         // A PermanentFailure implies we should probably just shut down the node since we're
83         // force-closing channels without even broadcasting!
84
85         fn persist_new_channel(&self, funding_txo: OutPoint, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
86                 let key = format!("monitors/{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
87                 match self.persist(&key, monitor) {
88                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
89                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
90                 }
91         }
92
93         fn update_persisted_channel(&self, funding_txo: OutPoint, _update: &Option<ChannelMonitorUpdate>, monitor: &ChannelMonitor<ChannelSigner>, _update_id: MonitorUpdateId) -> chain::ChannelMonitorUpdateStatus {
94                 let key = format!("monitors/{}_{}", funding_txo.txid.to_hex(), funding_txo.index);
95                 match self.persist(&key, monitor) {
96                         Ok(()) => chain::ChannelMonitorUpdateStatus::Completed,
97                         Err(_) => chain::ChannelMonitorUpdateStatus::PermanentFailure,
98                 }
99         }
100 }