Merge pull request #840 from jkczyz/2021-03-rescan-logic
[rust-lightning] / lightning / src / chain / mod.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 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
11
12 use bitcoin::blockdata::block::{Block, BlockHeader};
13 use bitcoin::blockdata::script::Script;
14 use bitcoin::blockdata::transaction::{Transaction, TxOut};
15 use bitcoin::hash_types::{BlockHash, Txid};
16
17 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
18 use chain::keysinterface::Sign;
19 use chain::transaction::OutPoint;
20
21 pub mod chaininterface;
22 pub mod chainmonitor;
23 pub mod channelmonitor;
24 pub mod transaction;
25 pub mod keysinterface;
26
27 /// An error when accessing the chain via [`Access`].
28 #[derive(Clone)]
29 pub enum AccessError {
30         /// The requested chain is unknown.
31         UnknownChain,
32
33         /// The requested transaction doesn't exist or hasn't confirmed.
34         UnknownTx,
35 }
36
37 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
38 /// UTXOs.
39 pub trait Access: Send + Sync {
40         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
41         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
42         /// is unknown.
43         ///
44         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
45         fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
46 }
47
48 /// The `Listen` trait is used to be notified of when blocks have been connected or disconnected
49 /// from the chain.
50 ///
51 /// Useful when needing to replay chain data upon startup or as new chain events occur.
52 pub trait Listen {
53         /// Notifies the listener that a block was added at the given height.
54         fn block_connected(&self, block: &Block, height: u32);
55
56         /// Notifies the listener that a block was removed at the given height.
57         fn block_disconnected(&self, header: &BlockHeader, height: u32);
58 }
59
60 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
61 /// blocks are connected and disconnected.
62 ///
63 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
64 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
65 /// channel state changes and HTLCs are resolved. See method documentation for specific
66 /// requirements.
67 ///
68 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
69 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
70 /// without taking any further action such as persisting the current state.
71 ///
72 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
73 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
74 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
75 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
76 /// multiple instances.
77 ///
78 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
79 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
80 /// [`PermanentFailure`]: channelmonitor::ChannelMonitorUpdateErr::PermanentFailure
81 pub trait Watch<ChannelSigner: Sign>: Send + Sync {
82         /// Watches a channel identified by `funding_txo` using `monitor`.
83         ///
84         /// Implementations are responsible for watching the chain for the funding transaction along
85         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
86         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
87         ///
88         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
89         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
90         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
91         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
92
93         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
94         ///
95         /// Implementations must call [`update_monitor`] with the given update. See
96         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
97         ///
98         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
99         /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
100         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
101
102         /// Returns any monitor events since the last call. Subsequent calls must only return new
103         /// events.
104         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent>;
105 }
106
107 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
108 /// channels.
109 ///
110 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
111 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
112 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
113 /// receiving full blocks from a chain source, any further filtering is unnecessary.
114 ///
115 /// After an output has been registered, subsequent block retrievals from the chain source must not
116 /// exclude any transactions matching the new criteria nor any in-block descendants of such
117 /// transactions.
118 ///
119 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
120 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
121 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
122 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
123 ///
124 /// [`TemporaryFailure`]: channelmonitor::ChannelMonitorUpdateErr::TemporaryFailure
125 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
126 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
127 pub trait Filter: Send + Sync {
128         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
129         /// a spending condition.
130         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
131
132         /// Registers interest in spends of a transaction output.
133         ///
134         /// Optionally, when `output.block_hash` is set, should return any transaction spending the
135         /// output that is found in the corresponding block along with its index.
136         ///
137         /// This return value is useful for Electrum clients in order to supply in-block descendant
138         /// transactions which otherwise were not included. This is not necessary for other clients if
139         /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
140         /// full block).
141         fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
142 }
143
144 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
145 ///
146 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
147 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
148 /// the return value of [`Filter::register_output`].
149 ///
150 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
151 /// may have been spent there. See [`Filter::register_output`] for details.
152 ///
153 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
154 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
155 pub struct WatchedOutput {
156         /// First block where the transaction output may have been spent.
157         pub block_hash: Option<BlockHash>,
158
159         /// Outpoint identifying the transaction output.
160         pub outpoint: OutPoint,
161
162         /// Spending condition of the transaction output.
163         pub script_pubkey: Script,
164 }
165
166 impl<T: Listen> Listen for std::ops::Deref<Target = T> {
167         fn block_connected(&self, block: &Block, height: u32) {
168                 (**self).block_connected(block, height);
169         }
170
171         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
172                 (**self).block_disconnected(header, height);
173         }
174 }
175
176 impl<T: std::ops::Deref, U: std::ops::Deref> Listen for (T, U)
177 where
178         T::Target: Listen,
179         U::Target: Listen,
180 {
181         fn block_connected(&self, block: &Block, height: u32) {
182                 self.0.block_connected(block, height);
183                 self.1.block_connected(block, height);
184         }
185
186         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
187                 self.0.block_disconnected(header, height);
188                 self.1.block_disconnected(header, height);
189         }
190 }