WIP: Common ChainListener implementations and example
[rust-lightning] / lightning / src / chain / chainmonitor.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Logic to connect off-chain channel management with on-chain transaction monitoring.
11 //!
12 //! [`ChainMonitor`] is an implementation of [`chain::Watch`] used both to process blocks and to
13 //! update [`ChannelMonitor`]s accordingly. If any on-chain events need further processing, it will
14 //! make those available as [`MonitorEvent`]s to be consumed.
15 //!
16 //! `ChainMonitor` is parameterized by an optional chain source, which must implement the
17 //! [`chain::Filter`] trait. This provides a mechanism to signal new relevant outputs back to light
18 //! clients, such that transactions spending those outputs are included in block data.
19 //!
20 //! `ChainMonitor` may be used directly to monitor channels locally or as a part of a distributed
21 //! setup to monitor channels remotely. In the latter case, a custom `chain::Watch` implementation
22 //! would be responsible for routing each update to a remote server and for retrieving monitor
23 //! events. The remote server would make use of `ChainMonitor` for block processing and for
24 //! servicing `ChannelMonitor` updates from the client.
25 //!
26 //! [`ChainMonitor`]: struct.ChainMonitor.html
27 //! [`chain::Filter`]: ../trait.Filter.html
28 //! [`chain::Watch`]: ../trait.Watch.html
29 //! [`ChannelMonitor`]: ../channelmonitor/struct.ChannelMonitor.html
30 //! [`MonitorEvent`]: ../channelmonitor/enum.MonitorEvent.html
31
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33
34 use chain;
35 use chain::ChainListener;
36 use chain::Filter;
37 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
38 use chain::channelmonitor;
39 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
40 use chain::transaction::{OutPoint, TransactionData};
41 use chain::keysinterface::Sign;
42 use util::logger::Logger;
43 use util::events;
44 use util::events::Event;
45
46 use std::collections::{HashMap, hash_map};
47 use std::sync::Mutex;
48 use std::ops::Deref;
49
50 /// An implementation of [`chain::Watch`] for monitoring channels.
51 ///
52 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
53 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
54 /// or used independently to monitor channels remotely. See the [module-level documentation] for
55 /// details.
56 ///
57 /// [`chain::Watch`]: ../trait.Watch.html
58 /// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
59 /// [module-level documentation]: index.html
60 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
61         where C::Target: chain::Filter,
62         T::Target: BroadcasterInterface,
63         F::Target: FeeEstimator,
64         L::Target: Logger,
65         P::Target: channelmonitor::Persist<ChannelSigner>,
66 {
67         /// The monitors
68         pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
69         chain_source: Option<C>,
70         broadcaster: T,
71         logger: L,
72         fee_estimator: F,
73         persister: P,
74 }
75
76 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
77 where C::Target: chain::Filter,
78             T::Target: BroadcasterInterface,
79             F::Target: FeeEstimator,
80             L::Target: Logger,
81             P::Target: channelmonitor::Persist<ChannelSigner>,
82 {
83         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
84         /// of a channel and reacting accordingly based on transactions in the connected block. See
85         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
86         /// be returned by [`chain::Watch::release_pending_monitor_events`].
87         ///
88         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
89         /// calls must not exclude any transactions matching the new outputs nor any in-block
90         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
91         /// updated `txdata`.
92         ///
93         /// [`ChannelMonitor::block_connected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_connected
94         /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
95         /// [`chain::Filter`]: ../trait.Filter.html
96         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
97                 let mut monitors = self.monitors.lock().unwrap();
98                 for monitor in monitors.values_mut() {
99                         let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
100
101                         if let Some(ref chain_source) = self.chain_source {
102                                 for (txid, outputs) in txn_outputs.drain(..) {
103                                         for (idx, output) in outputs.iter() {
104                                                 chain_source.register_output(&OutPoint { txid, index: *idx as u16 }, &output.script_pubkey);
105                                         }
106                                 }
107                         }
108                 }
109         }
110
111         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
112         /// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
113         /// details.
114         ///
115         /// [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
116         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
117                 let mut monitors = self.monitors.lock().unwrap();
118                 for monitor in monitors.values_mut() {
119                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
120                 }
121         }
122
123         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
124         ///
125         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
126         /// will call back to it indicating transactions and outputs of interest. This allows clients to
127         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
128         /// always need to fetch full blocks absent another means for determining which blocks contain
129         /// transactions relevant to the watched channels.
130         ///
131         /// [`chain::Filter`]: ../trait.Filter.html
132         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
133                 Self {
134                         monitors: Mutex::new(HashMap::new()),
135                         chain_source,
136                         broadcaster,
137                         logger,
138                         fee_estimator: feeest,
139                         persister,
140                 }
141         }
142 }
143
144 impl<ChannelSigner: Sign, C: Deref + Send + Sync, T: Deref + Send + Sync, F: Deref + Send + Sync, L: Deref + Send + Sync, P: Deref + Send + Sync>
145 ChainListener for ChainMonitor<ChannelSigner, C, T, F, L, P>
146 where
147         ChannelSigner: Sign,
148         C::Target: chain::Filter,
149         T::Target: BroadcasterInterface,
150         F::Target: FeeEstimator,
151         L::Target: Logger,
152         P::Target: channelmonitor::Persist<ChannelSigner>,
153 {
154         fn block_connected(&self, block: &Block, height: u32) {
155                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
156                 ChainMonitor::block_connected(self, &block.header, &txdata, height);
157         }
158
159         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
160                 ChainMonitor::block_disconnected(self, header, height);
161         }
162 }
163
164 impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
165 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
166 where C::Target: chain::Filter,
167             T::Target: BroadcasterInterface,
168             F::Target: FeeEstimator,
169             L::Target: Logger,
170             P::Target: channelmonitor::Persist<ChannelSigner>,
171 {
172         /// Adds the monitor that watches the channel referred to by the given outpoint.
173         ///
174         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
175         ///
176         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
177         /// monitors lock.
178         ///
179         /// [`chain::Filter`]: ../trait.Filter.html
180         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
181                 let mut monitors = self.monitors.lock().unwrap();
182                 let entry = match monitors.entry(funding_outpoint) {
183                         hash_map::Entry::Occupied(_) => {
184                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
185                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
186                         hash_map::Entry::Vacant(e) => e,
187                 };
188                 if let Err(e) = self.persister.persist_new_channel(funding_outpoint, &monitor) {
189                         log_error!(self.logger, "Failed to persist new channel data");
190                         return Err(e);
191                 }
192                 {
193                         let funding_txo = monitor.get_funding_txo();
194                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
195
196                         if let Some(ref chain_source) = self.chain_source {
197                                 chain_source.register_tx(&funding_txo.0.txid, &funding_txo.1);
198                                 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
199                                         for (idx, script_pubkey) in outputs.iter() {
200                                                 chain_source.register_output(&OutPoint { txid: *txid, index: *idx as u16 }, script_pubkey);
201                                         }
202                                 }
203                         }
204                 }
205                 entry.insert(monitor);
206                 Ok(())
207         }
208
209         /// Note that we persist the given `ChannelMonitor` update while holding the
210         /// `ChainMonitor` monitors lock.
211         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
212                 // Update the monitor that watches the channel referred to by the given outpoint.
213                 let mut monitors = self.monitors.lock().unwrap();
214                 match monitors.get_mut(&funding_txo) {
215                         None => {
216                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
217
218                                 // We should never ever trigger this from within ChannelManager. Technically a
219                                 // user could use this object with some proxying in between which makes this
220                                 // possible, but in tests and fuzzing, this should be a panic.
221                                 #[cfg(any(test, feature = "fuzztarget"))]
222                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
223                                 #[cfg(not(any(test, feature = "fuzztarget")))]
224                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
225                         },
226                         Some(orig_monitor) => {
227                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
228                                 let update_res = orig_monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
229                                 if let Err(e) = &update_res {
230                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
231                                 }
232                                 // Even if updating the monitor returns an error, the monitor's state will
233                                 // still be changed. So, persist the updated monitor despite the error.
234                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, orig_monitor);
235                                 if let Err(ref e) = persist_res {
236                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
237                                 }
238                                 if update_res.is_err() {
239                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
240                                 } else {
241                                         persist_res
242                                 }
243                         }
244                 }
245         }
246
247         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
248                 let mut pending_monitor_events = Vec::new();
249                 for chan in self.monitors.lock().unwrap().values_mut() {
250                         pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
251                 }
252                 pending_monitor_events
253         }
254 }
255
256 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
257         where C::Target: chain::Filter,
258               T::Target: BroadcasterInterface,
259               F::Target: FeeEstimator,
260               L::Target: Logger,
261               P::Target: channelmonitor::Persist<ChannelSigner>,
262 {
263         fn get_and_clear_pending_events(&self) -> Vec<Event> {
264                 let mut pending_events = Vec::new();
265                 for chan in self.monitors.lock().unwrap().values_mut() {
266                         pending_events.append(&mut chan.get_and_clear_pending_events());
267                 }
268                 pending_events
269         }
270 }