Merge pull request #856 from TheBlueMatt/2021-03-check-tx
[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 use bitcoin::blockdata::block::{Block, BlockHeader};
27
28 use chain;
29 use chain::{Filter, WatchedOutput};
30 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
31 use chain::channelmonitor;
32 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
33 use chain::transaction::{OutPoint, TransactionData};
34 use chain::keysinterface::Sign;
35 use util::logger::Logger;
36 use util::events;
37 use util::events::Event;
38
39 use std::collections::{HashMap, hash_map};
40 use std::sync::RwLock;
41 use std::ops::Deref;
42
43 /// An implementation of [`chain::Watch`] for monitoring channels.
44 ///
45 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
46 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
47 /// or used independently to monitor channels remotely. See the [module-level documentation] for
48 /// details.
49 ///
50 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
51 /// [module-level documentation]: crate::chain::chainmonitor
52 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
53         where C::Target: chain::Filter,
54         T::Target: BroadcasterInterface,
55         F::Target: FeeEstimator,
56         L::Target: Logger,
57         P::Target: channelmonitor::Persist<ChannelSigner>,
58 {
59         /// The monitors
60         pub monitors: RwLock<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
61         chain_source: Option<C>,
62         broadcaster: T,
63         logger: L,
64         fee_estimator: F,
65         persister: P,
66 }
67
68 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
69 where C::Target: chain::Filter,
70             T::Target: BroadcasterInterface,
71             F::Target: FeeEstimator,
72             L::Target: Logger,
73             P::Target: channelmonitor::Persist<ChannelSigner>,
74 {
75         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
76         /// of a channel and reacting accordingly based on transactions in the connected block. See
77         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
78         /// be returned by [`chain::Watch::release_pending_monitor_events`].
79         ///
80         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
81         /// calls must not exclude any transactions matching the new outputs nor any in-block
82         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
83         /// updated `txdata`.
84         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
85                 let mut dependent_txdata = Vec::new();
86                 let monitors = self.monitors.read().unwrap();
87                 for monitor in monitors.values() {
88                         let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
89
90                         // Register any new outputs with the chain source for filtering, storing any dependent
91                         // transactions from within the block that previously had not been included in txdata.
92                         if let Some(ref chain_source) = self.chain_source {
93                                 let block_hash = header.block_hash();
94                                 for (txid, outputs) in txn_outputs.drain(..) {
95                                         for (idx, output) in outputs.iter() {
96                                                 // Register any new outputs with the chain source for filtering and recurse
97                                                 // if it indicates that there are dependent transactions within the block
98                                                 // that had not been previously included in txdata.
99                                                 let output = WatchedOutput {
100                                                         block_hash: Some(block_hash),
101                                                         outpoint: OutPoint { txid, index: *idx as u16 },
102                                                         script_pubkey: output.script_pubkey.clone(),
103                                                 };
104                                                 if let Some(tx) = chain_source.register_output(output) {
105                                                         dependent_txdata.push(tx);
106                                                 }
107                                         }
108                                 }
109                         }
110                 }
111
112                 // Recursively call for any dependent transactions that were identified by the chain source.
113                 if !dependent_txdata.is_empty() {
114                         dependent_txdata.sort_unstable_by_key(|(index, _tx)| *index);
115                         dependent_txdata.dedup_by_key(|(index, _tx)| *index);
116                         let txdata: Vec<_> = dependent_txdata.iter().map(|(index, tx)| (*index, tx)).collect();
117                         self.block_connected(header, &txdata, height);
118                 }
119         }
120
121         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
122         /// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
123         /// details.
124         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
125                 let monitors = self.monitors.read().unwrap();
126                 for monitor in monitors.values() {
127                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
128                 }
129         }
130
131         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
132         ///
133         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
134         /// will call back to it indicating transactions and outputs of interest. This allows clients to
135         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
136         /// always need to fetch full blocks absent another means for determining which blocks contain
137         /// transactions relevant to the watched channels.
138         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
139                 Self {
140                         monitors: RwLock::new(HashMap::new()),
141                         chain_source,
142                         broadcaster,
143                         logger,
144                         fee_estimator: feeest,
145                         persister,
146                 }
147         }
148 }
149
150 impl<ChannelSigner: Sign, C: Deref + Send + Sync, T: Deref + Send + Sync, F: Deref + Send + Sync, L: Deref + Send + Sync, P: Deref + Send + Sync>
151 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
152 where
153         ChannelSigner: Sign,
154         C::Target: chain::Filter,
155         T::Target: BroadcasterInterface,
156         F::Target: FeeEstimator,
157         L::Target: Logger,
158         P::Target: channelmonitor::Persist<ChannelSigner>,
159 {
160         fn block_connected(&self, block: &Block, height: u32) {
161                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
162                 ChainMonitor::block_connected(self, &block.header, &txdata, height);
163         }
164
165         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
166                 ChainMonitor::block_disconnected(self, header, height);
167         }
168 }
169
170 impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
171 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
172 where C::Target: chain::Filter,
173             T::Target: BroadcasterInterface,
174             F::Target: FeeEstimator,
175             L::Target: Logger,
176             P::Target: channelmonitor::Persist<ChannelSigner>,
177 {
178         /// Adds the monitor that watches the channel referred to by the given outpoint.
179         ///
180         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
181         ///
182         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
183         /// monitors lock.
184         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
185                 let mut monitors = self.monitors.write().unwrap();
186                 let entry = match monitors.entry(funding_outpoint) {
187                         hash_map::Entry::Occupied(_) => {
188                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
189                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
190                         hash_map::Entry::Vacant(e) => e,
191                 };
192                 if let Err(e) = self.persister.persist_new_channel(funding_outpoint, &monitor) {
193                         log_error!(self.logger, "Failed to persist new channel data");
194                         return Err(e);
195                 }
196                 {
197                         let funding_txo = monitor.get_funding_txo();
198                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
199
200                         if let Some(ref chain_source) = self.chain_source {
201                                 monitor.load_outputs_to_watch(chain_source);
202                         }
203                 }
204                 entry.insert(monitor);
205                 Ok(())
206         }
207
208         /// Note that we persist the given `ChannelMonitor` update while holding the
209         /// `ChainMonitor` monitors lock.
210         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
211                 // Update the monitor that watches the channel referred to by the given outpoint.
212                 let monitors = self.monitors.read().unwrap();
213                 match monitors.get(&funding_txo) {
214                         None => {
215                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
216
217                                 // We should never ever trigger this from within ChannelManager. Technically a
218                                 // user could use this object with some proxying in between which makes this
219                                 // possible, but in tests and fuzzing, this should be a panic.
220                                 #[cfg(any(test, feature = "fuzztarget"))]
221                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
222                                 #[cfg(not(any(test, feature = "fuzztarget")))]
223                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
224                         },
225                         Some(monitor) => {
226                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
227                                 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
228                                 if let Err(e) = &update_res {
229                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
230                                 }
231                                 // Even if updating the monitor returns an error, the monitor's state will
232                                 // still be changed. So, persist the updated monitor despite the error.
233                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
234                                 if let Err(ref e) = persist_res {
235                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
236                                 }
237                                 if update_res.is_err() {
238                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
239                                 } else {
240                                         persist_res
241                                 }
242                         }
243                 }
244         }
245
246         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
247                 let mut pending_monitor_events = Vec::new();
248                 for monitor in self.monitors.read().unwrap().values() {
249                         pending_monitor_events.append(&mut monitor.get_and_clear_pending_monitor_events());
250                 }
251                 pending_monitor_events
252         }
253 }
254
255 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
256         where C::Target: chain::Filter,
257               T::Target: BroadcasterInterface,
258               F::Target: FeeEstimator,
259               L::Target: Logger,
260               P::Target: channelmonitor::Persist<ChannelSigner>,
261 {
262         fn get_and_clear_pending_events(&self) -> Vec<Event> {
263                 let mut pending_events = Vec::new();
264                 for monitor in self.monitors.read().unwrap().values() {
265                         pending_events.append(&mut monitor.get_and_clear_pending_events());
266                 }
267                 pending_events
268         }
269 }
270
271 #[cfg(test)]
272 mod tests {
273         use ::{check_added_monitors, get_local_commitment_txn};
274         use ln::features::InitFeatures;
275         use ln::functional_test_utils::*;
276         use util::events::EventsProvider;
277         use util::events::MessageSendEventsProvider;
278         use util::test_utils::{OnRegisterOutput, TxOutReference};
279
280         /// Tests that in-block dependent transactions are processed by `block_connected` when not
281         /// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
282         /// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the
283         /// commitment transaction itself. An Electrum client may filter the commitment transaction but
284         /// needs to return the HTLC transaction so it can be processed.
285         #[test]
286         fn connect_block_checks_dependent_transactions() {
287                 let chanmon_cfgs = create_chanmon_cfgs(2);
288                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
289                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
290                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
291                 let channel = create_announced_chan_between_nodes(
292                         &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
293
294                 // Send a payment, saving nodes[0]'s revoked commitment and HTLC-Timeout transactions.
295                 let (commitment_tx, htlc_tx) = {
296                         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000).0;
297                         let mut txn = get_local_commitment_txn!(nodes[0], channel.2);
298                         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 5_000_000);
299
300                         assert_eq!(txn.len(), 2);
301                         (txn.remove(0), txn.remove(0))
302                 };
303
304                 // Set expectations on nodes[1]'s chain source to return dependent transactions.
305                 let htlc_output = TxOutReference(commitment_tx.clone(), 0);
306                 let to_local_output = TxOutReference(commitment_tx.clone(), 1);
307                 let htlc_timeout_output = TxOutReference(htlc_tx.clone(), 0);
308                 nodes[1].chain_source
309                         .expect(OnRegisterOutput { with: htlc_output, returns: Some((1, htlc_tx)) })
310                         .expect(OnRegisterOutput { with: to_local_output, returns: None })
311                         .expect(OnRegisterOutput { with: htlc_timeout_output, returns: None });
312
313                 // Notify nodes[1] that nodes[0]'s revoked commitment transaction was mined. The chain
314                 // source should return the dependent HTLC transaction when the HTLC output is registered.
315                 mine_transaction(&nodes[1], &commitment_tx);
316
317                 // Clean up so uninteresting assertions don't fail.
318                 check_added_monitors!(nodes[1], 1);
319                 nodes[1].node.get_and_clear_pending_msg_events();
320                 nodes[1].node.get_and_clear_pending_events();
321         }
322 }