6c67f54f11a63b38d07c4da843870d5c48d2d372
[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::BlockHeader;
33
34 use chain;
35 use chain::Filter;
36 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
37 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, MonitorUpdateError};
38 use chain::transaction::{OutPoint, TransactionData};
39 use chain::keysinterface::ChannelKeys;
40 use util::logger::Logger;
41 use util::events;
42 use util::events::Event;
43
44 use std::collections::{HashMap, hash_map};
45 use std::sync::Mutex;
46 use std::ops::Deref;
47
48 /// An implementation of [`chain::Watch`] for monitoring channels.
49 ///
50 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
51 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
52 /// or used independently to monitor channels remotely. See the [module-level documentation] for
53 /// details.
54 ///
55 /// [`chain::Watch`]: ../trait.Watch.html
56 /// [`ChannelManager`]: ../../ln/channelmanager/struct.ChannelManager.html
57 /// [module-level documentation]: index.html
58 pub struct ChainMonitor<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref>
59         where C::Target: chain::Filter,
60         T::Target: BroadcasterInterface,
61         F::Target: FeeEstimator,
62         L::Target: Logger,
63 {
64         /// The monitors
65         pub monitors: Mutex<HashMap<OutPoint, ChannelMonitor<ChanSigner>>>,
66         chain_source: Option<C>,
67         broadcaster: T,
68         logger: L,
69         fee_estimator: F
70 }
71
72 impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> ChainMonitor<ChanSigner, C, T, F, L>
73         where C::Target: chain::Filter,
74               T::Target: BroadcasterInterface,
75               F::Target: FeeEstimator,
76               L::Target: Logger,
77 {
78         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
79         /// of a channel and reacting accordingly based on transactions in the connected block. See
80         /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
81         /// be returned by [`chain::Watch::release_pending_monitor_events`].
82         ///
83         /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
84         /// calls must not exclude any transactions matching the new outputs nor any in-block
85         /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
86         /// updated `txdata`.
87         ///
88         /// [`ChannelMonitor::block_connected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_connected
89         /// [`chain::Watch::release_pending_monitor_events`]: ../trait.Watch.html#tymethod.release_pending_monitor_events
90         /// [`chain::Filter`]: ../trait.Filter.html
91         pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
92                 let mut monitors = self.monitors.lock().unwrap();
93                 for monitor in monitors.values_mut() {
94                         let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
95
96                         if let Some(ref chain_source) = self.chain_source {
97                                 for (txid, outputs) in txn_outputs.drain(..) {
98                                         for (idx, output) in outputs.iter() {
99                                                 chain_source.register_output(&OutPoint { txid, index: *idx as u16 }, &output.script_pubkey);
100                                         }
101                                 }
102                         }
103                 }
104         }
105
106         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
107         /// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
108         /// details.
109         ///
110         /// [`ChannelMonitor::block_disconnected`]: ../channelmonitor/struct.ChannelMonitor.html#method.block_disconnected
111         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
112                 let mut monitors = self.monitors.lock().unwrap();
113                 for monitor in monitors.values_mut() {
114                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
115                 }
116         }
117
118         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
119         ///
120         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
121         /// will call back to it indicating transactions and outputs of interest. This allows clients to
122         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
123         /// always need to fetch full blocks absent another means for determining which blocks contain
124         /// transactions relevant to the watched channels.
125         ///
126         /// [`chain::Filter`]: ../trait.Filter.html
127         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F) -> Self {
128                 Self {
129                         monitors: Mutex::new(HashMap::new()),
130                         chain_source,
131                         broadcaster,
132                         logger,
133                         fee_estimator: feeest,
134                 }
135         }
136
137         /// Adds the monitor that watches the channel referred to by the given outpoint.
138         ///
139         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
140         ///
141         /// [`chain::Filter`]: ../trait.Filter.html
142         fn add_monitor(&self, outpoint: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), MonitorUpdateError> {
143                 let mut monitors = self.monitors.lock().unwrap();
144                 let entry = match monitors.entry(outpoint) {
145                         hash_map::Entry::Occupied(_) => return Err(MonitorUpdateError("Channel monitor for given outpoint is already present")),
146                         hash_map::Entry::Vacant(e) => e,
147                 };
148                 {
149                         let funding_txo = monitor.get_funding_txo();
150                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
151
152                         if let Some(ref chain_source) = self.chain_source {
153                                 chain_source.register_tx(&funding_txo.0.txid, &funding_txo.1);
154                                 for (txid, outputs) in monitor.get_outputs_to_watch().iter() {
155                                         for (idx, script_pubkey) in outputs.iter() {
156                                                 chain_source.register_output(&OutPoint { txid: *txid, index: *idx as u16 }, script_pubkey);
157                                         }
158                                 }
159                         }
160                 }
161                 entry.insert(monitor);
162                 Ok(())
163         }
164
165         /// Updates the monitor that watches the channel referred to by the given outpoint.
166         fn update_monitor(&self, outpoint: OutPoint, update: ChannelMonitorUpdate) -> Result<(), MonitorUpdateError> {
167                 let mut monitors = self.monitors.lock().unwrap();
168                 match monitors.get_mut(&outpoint) {
169                         Some(orig_monitor) => {
170                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(orig_monitor));
171                                 orig_monitor.update_monitor(update, &self.broadcaster, &self.logger)
172                         },
173                         None => Err(MonitorUpdateError("No such monitor registered"))
174                 }
175         }
176 }
177
178 impl<ChanSigner: ChannelKeys, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send> chain::Watch for ChainMonitor<ChanSigner, C, T, F, L>
179         where C::Target: chain::Filter,
180               T::Target: BroadcasterInterface,
181               F::Target: FeeEstimator,
182               L::Target: Logger,
183 {
184         type Keys = ChanSigner;
185
186         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChanSigner>) -> Result<(), ChannelMonitorUpdateErr> {
187                 match self.add_monitor(funding_txo, monitor) {
188                         Ok(_) => Ok(()),
189                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
190                 }
191         }
192
193         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
194                 match self.update_monitor(funding_txo, update) {
195                         Ok(_) => Ok(()),
196                         Err(_) => Err(ChannelMonitorUpdateErr::PermanentFailure),
197                 }
198         }
199
200         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
201                 let mut pending_monitor_events = Vec::new();
202                 for chan in self.monitors.lock().unwrap().values_mut() {
203                         pending_monitor_events.append(&mut chan.get_and_clear_pending_monitor_events());
204                 }
205                 pending_monitor_events
206         }
207 }
208
209 impl<ChanSigner: ChannelKeys, C: Deref, T: Deref, F: Deref, L: Deref> events::EventsProvider for ChainMonitor<ChanSigner, C, T, F, L>
210         where C::Target: chain::Filter,
211               T::Target: BroadcasterInterface,
212               F::Target: FeeEstimator,
213               L::Target: Logger,
214 {
215         fn get_and_clear_pending_events(&self) -> Vec<Event> {
216                 let mut pending_events = Vec::new();
217                 for chan in self.monitors.lock().unwrap().values_mut() {
218                         pending_events.append(&mut chan.get_and_clear_pending_events());
219                 }
220                 pending_events
221         }
222 }