1 // This file is Copyright its original authors, visible in version control
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
10 //! Logic to connect off-chain channel management with on-chain transaction monitoring.
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.
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.
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.
26 use bitcoin::blockdata::block::{Block, BlockHeader};
27 use bitcoin::hash_types::Txid;
30 use chain::{Filter, WatchedOutput};
31 use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
32 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, Balance, MonitorEvent, TransactionOutputs};
33 use chain::transaction::{OutPoint, TransactionData};
34 use chain::keysinterface::Sign;
35 use util::logger::Logger;
37 use util::events::EventHandler;
38 use ln::channelmanager::ChannelDetails;
44 /// `Persist` defines behavior for persisting channel monitors: this could mean
45 /// writing once to disk, and/or uploading to one or more backup services.
47 /// Note that for every new monitor, you **must** persist the new `ChannelMonitor`
48 /// to disk/backups. And, on every update, you **must** persist either the
49 /// `ChannelMonitorUpdate` or the updated monitor itself. Otherwise, there is risk
50 /// of situations such as revoking a transaction, then crashing before this
51 /// revocation can be persisted, then unintentionally broadcasting a revoked
52 /// transaction and losing money. This is a risk because previous channel states
53 /// are toxic, so it's important that whatever channel state is persisted is
55 pub trait Persist<ChannelSigner: Sign> {
56 /// Persist a new channel's data. The data can be stored any way you want, but
57 /// the identifier provided by Rust-Lightning is the channel's outpoint (and
58 /// it is up to you to maintain a correct mapping between the outpoint and the
59 /// stored channel data). Note that you **must** persist every new monitor to
60 /// disk. See the `Persist` trait documentation for more details.
62 /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`
63 /// and [`ChannelMonitorUpdateErr`] for requirements when returning errors.
65 /// [`Writeable::write`]: crate::util::ser::Writeable::write
66 fn persist_new_channel(&self, id: OutPoint, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
68 /// Update one channel's data. The provided `ChannelMonitor` has already
69 /// applied the given update.
71 /// Note that on every update, you **must** persist either the
72 /// `ChannelMonitorUpdate` or the updated monitor itself to disk/backups. See
73 /// the `Persist` trait documentation for more details.
75 /// If an implementer chooses to persist the updates only, they need to make
76 /// sure that all the updates are applied to the `ChannelMonitors` *before*
77 /// the set of channel monitors is given to the `ChannelManager`
78 /// deserialization routine. See [`ChannelMonitor::update_monitor`] for
79 /// applying a monitor update to a monitor. If full `ChannelMonitors` are
80 /// persisted, then there is no need to persist individual updates.
82 /// Note that there could be a performance tradeoff between persisting complete
83 /// channel monitors on every update vs. persisting only updates and applying
84 /// them in batches. The size of each monitor grows `O(number of state updates)`
85 /// whereas updates are small and `O(1)`.
87 /// See [`Writeable::write`] on [`ChannelMonitor`] for writing out a `ChannelMonitor`,
88 /// [`Writeable::write`] on [`ChannelMonitorUpdate`] for writing out an update, and
89 /// [`ChannelMonitorUpdateErr`] for requirements when returning errors.
91 /// [`Writeable::write`]: crate::util::ser::Writeable::write
92 fn update_persisted_channel(&self, id: OutPoint, update: &ChannelMonitorUpdate, data: &ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
95 /// An implementation of [`chain::Watch`] for monitoring channels.
97 /// Connected and disconnected blocks must be provided to `ChainMonitor` as documented by
98 /// [`chain::Watch`]. May be used in conjunction with [`ChannelManager`] to monitor channels locally
99 /// or used independently to monitor channels remotely. See the [module-level documentation] for
102 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
103 /// [module-level documentation]: crate::chain::chainmonitor
104 pub struct ChainMonitor<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
105 where C::Target: chain::Filter,
106 T::Target: BroadcasterInterface,
107 F::Target: FeeEstimator,
109 P::Target: Persist<ChannelSigner>,
112 pub monitors: RwLock<HashMap<OutPoint, ChannelMonitor<ChannelSigner>>>,
113 chain_source: Option<C>,
120 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
121 where C::Target: chain::Filter,
122 T::Target: BroadcasterInterface,
123 F::Target: FeeEstimator,
125 P::Target: Persist<ChannelSigner>,
127 /// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
128 /// of a channel and reacting accordingly based on transactions in the given chain data. See
129 /// [`ChannelMonitor::block_connected`] for details. Any HTLCs that were resolved on chain will
130 /// be returned by [`chain::Watch::release_pending_monitor_events`].
132 /// Calls back to [`chain::Filter`] if any monitor indicated new outputs to watch. Subsequent
133 /// calls must not exclude any transactions matching the new outputs nor any in-block
134 /// descendants of such transactions. It is not necessary to re-fetch the block to obtain
135 /// updated `txdata`.
136 fn process_chain_data<FN>(&self, header: &BlockHeader, txdata: &TransactionData, process: FN)
138 FN: Fn(&ChannelMonitor<ChannelSigner>, &TransactionData) -> Vec<TransactionOutputs>
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);
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,
159 if let Some(tx) = chain_source.register_output(output) {
160 dependent_txdata.push(tx);
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);
176 /// Creates a new `ChainMonitor` used to watch on-chain activity pertaining to channels.
178 /// When an optional chain source implementing [`chain::Filter`] is provided, the chain monitor
179 /// will call back to it indicating transactions and outputs of interest. This allows clients to
180 /// pre-filter blocks or only fetch blocks matching a compact filter. Otherwise, clients may
181 /// always need to fetch full blocks absent another means for determining which blocks contain
182 /// transactions relevant to the watched channels.
183 pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P) -> Self {
185 monitors: RwLock::new(HashMap::new()),
189 fee_estimator: feeest,
194 /// Gets the balances in the contained [`ChannelMonitor`]s which are claimable on-chain or
195 /// claims which are awaiting confirmation.
197 /// Includes the balances from each [`ChannelMonitor`] *except* those included in
198 /// `ignored_channels`, allowing you to filter out balances from channels which are still open
199 /// (and whose balance should likely be pulled from the [`ChannelDetails`]).
201 /// See [`ChannelMonitor::get_claimable_balances`] for more details on the exact criteria for
202 /// inclusion in the return value.
203 pub fn get_claimable_balances(&self, ignored_channels: &[&ChannelDetails]) -> Vec<Balance> {
204 let mut ret = Vec::new();
205 let monitors = self.monitors.read().unwrap();
206 for (_, monitor) in monitors.iter().filter(|(funding_outpoint, _)| {
207 for chan in ignored_channels {
208 if chan.funding_txo.as_ref() == Some(funding_outpoint) {
214 ret.append(&mut monitor.get_claimable_balances());
219 #[cfg(any(test, feature = "fuzztarget", feature = "_test_utils"))]
220 pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
221 use util::events::EventsProvider;
222 let events = core::cell::RefCell::new(Vec::new());
223 let event_handler = |event: &events::Event| events.borrow_mut().push(event.clone());
224 self.process_pending_events(&event_handler);
229 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
230 chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
232 C::Target: chain::Filter,
233 T::Target: BroadcasterInterface,
234 F::Target: FeeEstimator,
236 P::Target: Persist<ChannelSigner>,
238 fn block_connected(&self, block: &Block, height: u32) {
239 let header = &block.header;
240 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
241 log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
242 self.process_chain_data(header, &txdata, |monitor, txdata| {
243 monitor.block_connected(
244 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
248 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
249 let monitors = self.monitors.read().unwrap();
250 log_debug!(self.logger, "Latest block {} at height {} removed via block_disconnected", header.block_hash(), height);
251 for monitor in monitors.values() {
252 monitor.block_disconnected(
253 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
258 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
259 chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
261 C::Target: chain::Filter,
262 T::Target: BroadcasterInterface,
263 F::Target: FeeEstimator,
265 P::Target: Persist<ChannelSigner>,
267 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
268 log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
269 self.process_chain_data(header, txdata, |monitor, txdata| {
270 monitor.transactions_confirmed(
271 header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
275 fn transaction_unconfirmed(&self, txid: &Txid) {
276 log_debug!(self.logger, "Transaction {} reorganized out of chain", txid);
277 let monitors = self.monitors.read().unwrap();
278 for monitor in monitors.values() {
279 monitor.transaction_unconfirmed(txid, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
283 fn best_block_updated(&self, header: &BlockHeader, height: u32) {
284 log_debug!(self.logger, "New best block {} at height {} provided via best_block_updated", header.block_hash(), height);
285 self.process_chain_data(header, &[], |monitor, txdata| {
286 // While in practice there shouldn't be any recursive calls when given empty txdata,
287 // it's still possible if a chain::Filter implementation returns a transaction.
288 debug_assert!(txdata.is_empty());
289 monitor.best_block_updated(
290 header, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger)
294 fn get_relevant_txids(&self) -> Vec<Txid> {
295 let mut txids = Vec::new();
296 let monitors = self.monitors.read().unwrap();
297 for monitor in monitors.values() {
298 txids.append(&mut monitor.get_relevant_txids());
301 txids.sort_unstable();
307 impl<ChannelSigner: Sign, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
308 chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
309 where C::Target: chain::Filter,
310 T::Target: BroadcasterInterface,
311 F::Target: FeeEstimator,
313 P::Target: Persist<ChannelSigner>,
315 /// Adds the monitor that watches the channel referred to by the given outpoint.
317 /// Calls back to [`chain::Filter`] with the funding transaction and outputs to watch.
319 /// Note that we persist the given `ChannelMonitor` while holding the `ChainMonitor`
321 fn watch_channel(&self, funding_outpoint: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr> {
322 let mut monitors = self.monitors.write().unwrap();
323 let entry = match monitors.entry(funding_outpoint) {
324 hash_map::Entry::Occupied(_) => {
325 log_error!(self.logger, "Failed to add new channel data: channel monitor for given outpoint is already present");
326 return Err(ChannelMonitorUpdateErr::PermanentFailure)},
327 hash_map::Entry::Vacant(e) => e,
329 if let Err(e) = self.persister.persist_new_channel(funding_outpoint, &monitor) {
330 log_error!(self.logger, "Failed to persist new channel data");
334 let funding_txo = monitor.get_funding_txo();
335 log_trace!(self.logger, "Got new Channel Monitor for channel {}", log_bytes!(funding_txo.0.to_channel_id()[..]));
337 if let Some(ref chain_source) = self.chain_source {
338 monitor.load_outputs_to_watch(chain_source);
341 entry.insert(monitor);
345 /// Note that we persist the given `ChannelMonitor` update while holding the
346 /// `ChainMonitor` monitors lock.
347 fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr> {
348 // Update the monitor that watches the channel referred to by the given outpoint.
349 let monitors = self.monitors.read().unwrap();
350 match monitors.get(&funding_txo) {
352 log_error!(self.logger, "Failed to update channel monitor: no such monitor registered");
354 // We should never ever trigger this from within ChannelManager. Technically a
355 // user could use this object with some proxying in between which makes this
356 // possible, but in tests and fuzzing, this should be a panic.
357 #[cfg(any(test, feature = "fuzztarget"))]
358 panic!("ChannelManager generated a channel update for a channel that was not yet registered!");
359 #[cfg(not(any(test, feature = "fuzztarget")))]
360 Err(ChannelMonitorUpdateErr::PermanentFailure)
363 log_trace!(self.logger, "Updating Channel Monitor for channel {}", log_funding_info!(monitor));
364 let update_res = monitor.update_monitor(&update, &self.broadcaster, &self.fee_estimator, &self.logger);
365 if let Err(e) = &update_res {
366 log_error!(self.logger, "Failed to update channel monitor: {:?}", e);
368 // Even if updating the monitor returns an error, the monitor's state will
369 // still be changed. So, persist the updated monitor despite the error.
370 let persist_res = self.persister.update_persisted_channel(funding_txo, &update, monitor);
371 if let Err(ref e) = persist_res {
372 log_error!(self.logger, "Failed to persist channel monitor update: {:?}", e);
374 if update_res.is_err() {
375 Err(ChannelMonitorUpdateErr::PermanentFailure)
383 fn release_pending_monitor_events(&self) -> Vec<MonitorEvent> {
384 let mut pending_monitor_events = Vec::new();
385 for monitor in self.monitors.read().unwrap().values() {
386 pending_monitor_events.append(&mut monitor.get_and_clear_pending_monitor_events());
388 pending_monitor_events
392 impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
393 where C::Target: chain::Filter,
394 T::Target: BroadcasterInterface,
395 F::Target: FeeEstimator,
397 P::Target: Persist<ChannelSigner>,
399 /// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
401 /// An [`EventHandler`] may safely call back to the provider, though this shouldn't be needed in
402 /// order to handle these events.
404 /// [`SpendableOutputs`]: events::Event::SpendableOutputs
405 fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {
406 let mut pending_events = Vec::new();
407 for monitor in self.monitors.read().unwrap().values() {
408 pending_events.append(&mut monitor.get_and_clear_pending_events());
410 for event in pending_events.drain(..) {
411 handler.handle_event(&event);
418 use ::{check_added_monitors, get_local_commitment_txn};
419 use ln::features::InitFeatures;
420 use ln::functional_test_utils::*;
421 use util::events::MessageSendEventsProvider;
422 use util::test_utils::{OnRegisterOutput, TxOutReference};
424 /// Tests that in-block dependent transactions are processed by `block_connected` when not
425 /// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
426 /// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the
427 /// commitment transaction itself. An Electrum client may filter the commitment transaction but
428 /// needs to return the HTLC transaction so it can be processed.
430 fn connect_block_checks_dependent_transactions() {
431 let chanmon_cfgs = create_chanmon_cfgs(2);
432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
434 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
435 let channel = create_announced_chan_between_nodes(
436 &nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
438 // Send a payment, saving nodes[0]'s revoked commitment and HTLC-Timeout transactions.
439 let (commitment_tx, htlc_tx) = {
440 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000).0;
441 let mut txn = get_local_commitment_txn!(nodes[0], channel.2);
442 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
444 assert_eq!(txn.len(), 2);
445 (txn.remove(0), txn.remove(0))
448 // Set expectations on nodes[1]'s chain source to return dependent transactions.
449 let htlc_output = TxOutReference(commitment_tx.clone(), 0);
450 let to_local_output = TxOutReference(commitment_tx.clone(), 1);
451 let htlc_timeout_output = TxOutReference(htlc_tx.clone(), 0);
452 nodes[1].chain_source
453 .expect(OnRegisterOutput { with: htlc_output, returns: Some((1, htlc_tx)) })
454 .expect(OnRegisterOutput { with: to_local_output, returns: None })
455 .expect(OnRegisterOutput { with: htlc_timeout_output, returns: None });
457 // Notify nodes[1] that nodes[0]'s revoked commitment transaction was mined. The chain
458 // source should return the dependent HTLC transaction when the HTLC output is registered.
459 mine_transaction(&nodes[1], &commitment_tx);
461 // Clean up so uninteresting assertions don't fail.
462 check_added_monitors!(nodes[1], 1);
463 nodes[1].node.get_and_clear_pending_msg_events();
464 nodes[1].node.get_and_clear_pending_events();