Use the new `load_outputs_to_watch` util in `ChainMonitor`
[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::Filter;
36 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
37 use chain::channelmonitor;
38 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
39 use chain::transaction::{OutPoint, TransactionData};
40 use chain::keysinterface::Sign;
41 use util::logger::Logger;
42 use util::events;
43 use util::events::Event;
44
45 use std::collections::{HashMap, hash_map};
46 use std::sync::RwLock;
47 use std::ops::Deref;
48
49 /// An implementation of [`chain::Watch`] for monitoring channels.
50 ///
51 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
52 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
53 /// or used independently to monitor channels remotely. See the [module-level documentation] for
54 /// details.
55 ///
56 /// [`chain::Watch`]: ../trait.Watch.html
57 /// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
58 /// [module-level documentation]: index.html
59 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
60         where C::Target: chain::Filter,
61         T::Target: BroadcasterInterface,
62         F::Target: FeeEstimator,
63         L::Target: Logger,
64         P::Target: channelmonitor::Persist<ChannelSigner>,
65 {
66         /// The monitors
67         pub monitors: RwLock<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
68         chain_source: Option<C>,
69         broadcaster: T,
70         logger: L,
71         fee_estimator: F,
72         persister: P,
73 }
74
75 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
76 where C::Target: chain::Filter,
77             T::Target: BroadcasterInterface,
78             F::Target: FeeEstimator,
79             L::Target: Logger,
80             P::Target: channelmonitor::Persist<ChannelSigner>,
81 {
82         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
83         /// of a channel and reacting accordingly based on transactions in the connected block. See
84         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
85         /// be returned by [`chain::Watch::release_pending_monitor_events`].
86         ///
87         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
88         /// calls must not exclude any transactions matching the new outputs nor any in-block
89         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
90         /// updated `txdata`.
91         ///
92         /// [`ChannelMonitor::block_connected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_connected
93         /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
94         /// [`chain::Filter`]: ../trait.Filter.html
95         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
96                 let monitors = self.monitors.read().unwrap();
97                 for monitor in monitors.values() {
98                         let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
99
100                         if let Some(ref chain_source) = self.chain_source {
101                                 for (txid, outputs) in txn_outputs.drain(..) {
102                                         for (idx, output) in outputs.iter() {
103                                                 chain_source.register_output(&OutPoint { txid, index: *idx as u16 }, &output.script_pubkey);
104                                         }
105                                 }
106                         }
107                 }
108         }
109
110         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
111         /// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
112         /// details.
113         ///
114         /// [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
115         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
116                 let monitors = self.monitors.read().unwrap();
117                 for monitor in monitors.values() {
118                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
119                 }
120         }
121
122         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
123         ///
124         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
125         /// will call back to it indicating transactions and outputs of interest. This allows clients to
126         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
127         /// always need to fetch full blocks absent another means for determining which blocks contain
128         /// transactions relevant to the watched channels.
129         ///
130         /// [`chain::Filter`]: ../trait.Filter.html
131         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
132                 Self {
133                         monitors: RwLock::new(HashMap::new()),
134                         chain_source,
135                         broadcaster,
136                         logger,
137                         fee_estimator: feeest,
138                         persister,
139                 }
140         }
141 }
142
143 impl<ChannelSigner: Sign, C: Deref + Send + Sync, T: Deref + Send + Sync, F: Deref + Send + Sync, L: Deref + Send + Sync, P: Deref + Send + Sync>
144 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
145 where
146         ChannelSigner: Sign,
147         C::Target: chain::Filter,
148         T::Target: BroadcasterInterface,
149         F::Target: FeeEstimator,
150         L::Target: Logger,
151         P::Target: channelmonitor::Persist<ChannelSigner>,
152 {
153         fn block_connected(&self, block: &Block, height: u32) {
154                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
155                 ChainMonitor::block_connected(self, &block.header, &txdata, height);
156         }
157
158         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
159                 ChainMonitor::block_disconnected(self, header, height);
160         }
161 }
162
163 impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
164 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
165 where C::Target: chain::Filter,
166             T::Target: BroadcasterInterface,
167             F::Target: FeeEstimator,
168             L::Target: Logger,
169             P::Target: channelmonitor::Persist<ChannelSigner>,
170 {
171         /// Adds the monitor that watches the channel referred to by the given outpoint.
172         ///
173         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
174         ///
175         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
176         /// monitors lock.
177         ///
178         /// [`chain::Filter`]: ../trait.Filter.html
179         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
180                 let mut monitors = self.monitors.write().unwrap();
181                 let entry = match monitors.entry(funding_outpoint) {
182                         hash_map::Entry::Occupied(_) => {
183                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
184                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
185                         hash_map::Entry::Vacant(e) => e,
186                 };
187                 if let Err(e) = self.persister.persist_new_channel(funding_outpoint, &monitor) {
188                         log_error!(self.logger, "Failed to persist new channel data");
189                         return Err(e);
190                 }
191                 {
192                         let funding_txo = monitor.get_funding_txo();
193                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
194
195                         if let Some(ref chain_source) = self.chain_source {
196                                 monitor.load_outputs_to_watch(chain_source);
197                         }
198                 }
199                 entry.insert(monitor);
200                 Ok(())
201         }
202
203         /// Note that we persist the given `ChannelMonitor` update while holding the
204         /// `ChainMonitor` monitors lock.
205         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
206                 // Update the monitor that watches the channel referred to by the given outpoint.
207                 let monitors = self.monitors.read().unwrap();
208                 match monitors.get(&funding_txo) {
209                         None => {
210                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
211
212                                 // We should never ever trigger this from within ChannelManager. Technically a
213                                 // user could use this object with some proxying in between which makes this
214                                 // possible, but in tests and fuzzing, this should be a panic.
215                                 #[cfg(any(test, feature = "fuzztarget"))]
216                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
217                                 #[cfg(not(any(test, feature = "fuzztarget")))]
218                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
219                         },
220                         Some(monitor) => {
221                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
222                                 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
223                                 if let Err(e) = &update_res {
224                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
225                                 }
226                                 // Even if updating the monitor returns an error, the monitor's state will
227                                 // still be changed. So, persist the updated monitor despite the error.
228                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
229                                 if let Err(ref e) = persist_res {
230                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
231                                 }
232                                 if update_res.is_err() {
233                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
234                                 } else {
235                                         persist_res
236                                 }
237                         }
238                 }
239         }
240
241         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
242                 let mut pending_monitor_events = Vec::new();
243                 for monitor in self.monitors.read().unwrap().values() {
244                         pending_monitor_events.append(&mut monitor.get_and_clear_pending_monitor_events());
245                 }
246                 pending_monitor_events
247         }
248 }
249
250 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
251         where C::Target: chain::Filter,
252               T::Target: BroadcasterInterface,
253               F::Target: FeeEstimator,
254               L::Target: Logger,
255               P::Target: channelmonitor::Persist<ChannelSigner>,
256 {
257         fn get_and_clear_pending_events(&self) -> Vec<Event> {
258                 let mut pending_events = Vec::new();
259                 for monitor in self.monitors.read().unwrap().values() {
260                         pending_events.append(&mut monitor.get_and_clear_pending_events());
261                 }
262                 pending_events
263         }
264 }