234e60b4c5967d7335711cbed1fd20da73e3c245
[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 monitors = self.monitors.read().unwrap();
86                 for monitor in monitors.values() {
87                         let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
88
89                         if let Some(ref chain_source) = self.chain_source {
90                                 let block_hash = header.block_hash();
91                                 for (txid, outputs) in txn_outputs.drain(..) {
92                                         for (idx, output) in outputs.iter() {
93                                                 chain_source.register_output(WatchedOutput {
94                                                         block_hash: Some(block_hash),
95                                                         outpoint: OutPoint { txid, index: *idx as u16 },
96                                                         script_pubkey: output.script_pubkey.clone(),
97                                                 });
98                                         }
99                                 }
100                         }
101                 }
102         }
103
104         /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
105         /// of a channel based on the disconnected block. See [`ChannelMonitor::block_disconnected`] for
106         /// details.
107         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
108                 let monitors = self.monitors.read().unwrap();
109                 for monitor in monitors.values() {
110                         monitor.block_disconnected(header, disconnected_height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
111                 }
112         }
113
114         /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
115         ///
116         /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
117         /// will call back to it indicating transactions and outputs of interest. This allows clients to
118         /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
119         /// always need to fetch full blocks absent another means for determining which blocks contain
120         /// transactions relevant to the watched channels.
121         pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
122                 Self {
123                         monitors: RwLock::new(HashMap::new()),
124                         chain_source,
125                         broadcaster,
126                         logger,
127                         fee_estimator: feeest,
128                         persister,
129                 }
130         }
131 }
132
133 impl<ChannelSigner: Sign, C: Deref + Send + Sync, T: Deref + Send + Sync, F: Deref + Send + Sync, L: Deref + Send + Sync, P: Deref + Send + Sync>
134 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
135 where
136         ChannelSigner: Sign,
137         C::Target: chain::Filter,
138         T::Target: BroadcasterInterface,
139         F::Target: FeeEstimator,
140         L::Target: Logger,
141         P::Target: channelmonitor::Persist<ChannelSigner>,
142 {
143         fn block_connected(&self, block: &Block, height: u32) {
144                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
145                 ChainMonitor::block_connected(self, &block.header, &txdata, height);
146         }
147
148         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
149                 ChainMonitor::block_disconnected(self, header, height);
150         }
151 }
152
153 impl<ChannelSigner: Sign, C: Deref + Sync + Send, T: Deref + Sync + Send, F: Deref + Sync + Send, L: Deref + Sync + Send, P: Deref + Sync + Send>
154 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
155 where C::Target: chain::Filter,
156             T::Target: BroadcasterInterface,
157             F::Target: FeeEstimator,
158             L::Target: Logger,
159             P::Target: channelmonitor::Persist<ChannelSigner>,
160 {
161         /// Adds the monitor that watches the channel referred to by the given outpoint.
162         ///
163         /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
164         ///
165         /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
166         /// monitors lock.
167         fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
168                 let mut monitors = self.monitors.write().unwrap();
169                 let entry = match monitors.entry(funding_outpoint) {
170                         hash_map::Entry::Occupied(_) => {
171                                 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
172                                 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
173                         hash_map::Entry::Vacant(e) => e,
174                 };
175                 if let Err(e) = self.persister.persist_new_channel(funding_outpoint, &monitor) {
176                         log_error!(self.logger, "Failed to persist new channel data");
177                         return Err(e);
178                 }
179                 {
180                         let funding_txo = monitor.get_funding_txo();
181                         log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
182
183                         if let Some(ref chain_source) = self.chain_source {
184                                 monitor.load_outputs_to_watch(chain_source);
185                         }
186                 }
187                 entry.insert(monitor);
188                 Ok(())
189         }
190
191         /// Note that we persist the given `ChannelMonitor` update while holding the
192         /// `ChainMonitor` monitors lock.
193         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
194                 // Update the monitor that watches the channel referred to by the given outpoint.
195                 let monitors = self.monitors.read().unwrap();
196                 match monitors.get(&funding_txo) {
197                         None => {
198                                 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
199
200                                 // We should never ever trigger this from within ChannelManager. Technically a
201                                 // user could use this object with some proxying in between which makes this
202                                 // possible, but in tests and fuzzing, this should be a panic.
203                                 #[cfg(any(test, feature = "fuzztarget"))]
204                                 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
205                                 #[cfg(not(any(test, feature = "fuzztarget")))]
206                                 Err(ChannelMonitorUpdateErr::PermanentFailure)
207                         },
208                         Some(monitor) => {
209                                 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
210                                 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
211                                 if let Err(e) = &update_res {
212                                         log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
213                                 }
214                                 // Even if updating the monitor returns an error, the monitor's state will
215                                 // still be changed. So, persist the updated monitor despite the error.
216                                 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
217                                 if let Err(ref e) = persist_res {
218                                         log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
219                                 }
220                                 if update_res.is_err() {
221                                         Err(ChannelMonitorUpdateErr::PermanentFailure)
222                                 } else {
223                                         persist_res
224                                 }
225                         }
226                 }
227         }
228
229         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
230                 let mut pending_monitor_events = Vec::new();
231                 for monitor in self.monitors.read().unwrap().values() {
232                         pending_monitor_events.append(&mut monitor.get_and_clear_pending_monitor_events());
233                 }
234                 pending_monitor_events
235         }
236 }
237
238 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
239         where 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 get_and_clear_pending_events(&self) -> Vec<Event> {
246                 let mut pending_events = Vec::new();
247                 for monitor in self.monitors.read().unwrap().values() {
248                         pending_events.append(&mut monitor.get_and_clear_pending_events());
249                 }
250                 pending_events
251         }
252 }