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