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