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