Expose the current best chain tip from ChannelManager + Monitors
[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::constants::genesis_block;
14 use bitcoin::blockdata::script::Script;
15 use bitcoin::blockdata::transaction::{Transaction, TxOut};
16 use bitcoin::hash_types::{BlockHash, Txid};
17 use bitcoin::network::constants::Network;
18
19 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
20 use chain::keysinterface::Sign;
21 use chain::transaction::{OutPoint, TransactionData};
22
23 use prelude::*;
24
25 pub mod chaininterface;
26 pub mod chainmonitor;
27 pub mod channelmonitor;
28 pub mod transaction;
29 pub mod keysinterface;
30 pub(crate) mod onchaintx;
31 pub(crate) mod package;
32
33 /// The best known block as identified by its hash and height.
34 #[derive(Clone, Copy, PartialEq)]
35 pub struct BestBlock {
36         block_hash: BlockHash,
37         height: u32,
38 }
39
40 impl BestBlock {
41         /// Returns the best block from the genesis of the given network.
42         pub fn from_genesis(network: Network) -> Self {
43                 BestBlock {
44                         block_hash: genesis_block(network).header.block_hash(),
45                         height: 0,
46                 }
47         }
48
49         /// Returns the best block as identified by the given block hash and height.
50         pub fn new(block_hash: BlockHash, height: u32) -> Self {
51                 BestBlock { block_hash, height }
52         }
53
54         /// Returns the best block hash.
55         pub fn block_hash(&self) -> BlockHash { self.block_hash }
56
57         /// Returns the best block height.
58         pub fn height(&self) -> u32 { self.height }
59 }
60
61 /// An error when accessing the chain via [`Access`].
62 #[derive(Clone)]
63 pub enum AccessError {
64         /// The requested chain is unknown.
65         UnknownChain,
66
67         /// The requested transaction doesn't exist or hasn't confirmed.
68         UnknownTx,
69 }
70
71 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
72 /// UTXOs.
73 pub trait Access {
74         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
75         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
76         /// is unknown.
77         ///
78         /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
79         fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
80 }
81
82 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
83 /// chain.
84 ///
85 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
86 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
87 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
88 /// when needed.
89 pub trait Listen {
90         /// Notifies the listener that a block was added at the given height.
91         fn block_connected(&self, block: &Block, height: u32);
92
93         /// Notifies the listener that a block was removed at the given height.
94         fn block_disconnected(&self, header: &BlockHeader, height: u32);
95 }
96
97 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
98 /// unconfirmed during a chain reorganization.
99 ///
100 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
101 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
102 /// related to registered transactions and outputs. Upon notification, it would pass along the
103 /// matching transactions using this interface.
104 ///
105 /// # Use
106 ///
107 /// The intended use is as follows:
108 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
109 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
110 ///   that has been reorganized out of the chain.
111 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
112 ///
113 /// # Order
114 ///
115 /// Clients must call these methods in chain order. Specifically:
116 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
117 ///   block.
118 /// - Dependent transactions within the same block must be given in topological order, possibly in
119 ///   separate calls.
120 /// - Unconfirmed transactions must be given after the original confirmations and before any
121 ///   reconfirmation.
122 ///
123 /// See individual method documentation for further details.
124 ///
125 /// [`transactions_confirmed`]: Self::transactions_confirmed
126 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
127 /// [`best_block_updated`]: Self::best_block_updated
128 /// [`get_relevant_txids`]: Self::get_relevant_txids
129 pub trait Confirm {
130         /// Processes transactions confirmed in a block with a given header and height.
131         ///
132         /// Should be called for any transactions registered by [`Filter::register_tx`] or any
133         /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
134         /// appearing in the same block do not need to be included in the same call; instead, multiple
135         /// calls with additional transactions may be made so long as they are made in [chain order].
136         ///
137         /// May be called before or after [`best_block_updated`] for the corresponding block. However,
138         /// in the event of a chain reorganization, it must not be called with a `header` that is no
139         /// longer in the chain as of the last call to [`best_block_updated`].
140         ///
141         /// [chain order]: Confirm#Order
142         /// [`best_block_updated`]: Self::best_block_updated
143         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
144
145         /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
146         ///
147         /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
148         /// reorganized out of the best chain. Once called, the given transaction should not be returned
149         /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
150         ///
151         /// [`get_relevant_txids`]: Self::get_relevant_txids
152         /// [`transactions_confirmed`]: Self::transactions_confirmed
153         fn transaction_unconfirmed(&self, txid: &Txid);
154
155         /// Processes an update to the best header connected at the given height.
156         ///
157         /// Should be called when a new header is available but may be skipped for intermediary blocks
158         /// if they become available at the same time.
159         fn best_block_updated(&self, header: &BlockHeader, height: u32);
160
161         /// Returns transactions that should be monitored for reorganization out of the chain.
162         ///
163         /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
164         /// confirmations to be safe from a chain reorganization. Should not include any transactions
165         /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
166         ///
167         /// May be called to determine the subset of transactions that must still be monitored for
168         /// reorganization. Will be idempotent between calls but may change as a result of calls to the
169         /// other interface methods. Thus, this is useful to determine which transactions may need to be
170         /// given to [`transaction_unconfirmed`].
171         ///
172         /// [`transactions_confirmed`]: Self::transactions_confirmed
173         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
174         fn get_relevant_txids(&self) -> Vec<Txid>;
175 }
176
177 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
178 /// blocks are connected and disconnected.
179 ///
180 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
181 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
182 /// channel state changes and HTLCs are resolved. See method documentation for specific
183 /// requirements.
184 ///
185 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
186 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
187 /// without taking any further action such as persisting the current state.
188 ///
189 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
190 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
191 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
192 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
193 /// multiple instances.
194 ///
195 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
196 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
197 /// [`PermanentFailure`]: channelmonitor::ChannelMonitorUpdateErr::PermanentFailure
198 pub trait Watch<ChannelSigner: Sign> {
199         /// Watches a channel identified by `funding_txo` using `monitor`.
200         ///
201         /// Implementations are responsible for watching the chain for the funding transaction along
202         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
203         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
204         ///
205         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
206         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
207         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
208         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
209
210         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
211         ///
212         /// Implementations must call [`update_monitor`] with the given update. See
213         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
214         ///
215         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
216         /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
217         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
218
219         /// Returns any monitor events since the last call. Subsequent calls must only return new
220         /// events.
221         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent>;
222 }
223
224 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
225 /// channels.
226 ///
227 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
228 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
229 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
230 /// receiving full blocks from a chain source, any further filtering is unnecessary.
231 ///
232 /// After an output has been registered, subsequent block retrievals from the chain source must not
233 /// exclude any transactions matching the new criteria nor any in-block descendants of such
234 /// transactions.
235 ///
236 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
237 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
238 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
239 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
240 ///
241 /// [`TemporaryFailure`]: channelmonitor::ChannelMonitorUpdateErr::TemporaryFailure
242 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
243 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
244 pub trait Filter {
245         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
246         /// a spending condition.
247         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
248
249         /// Registers interest in spends of a transaction output.
250         ///
251         /// Optionally, when `output.block_hash` is set, should return any transaction spending the
252         /// output that is found in the corresponding block along with its index.
253         ///
254         /// This return value is useful for Electrum clients in order to supply in-block descendant
255         /// transactions which otherwise were not included. This is not necessary for other clients if
256         /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
257         /// full block).
258         fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
259 }
260
261 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
262 ///
263 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
264 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
265 /// the return value of [`Filter::register_output`].
266 ///
267 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
268 /// may have been spent there. See [`Filter::register_output`] for details.
269 ///
270 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
271 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
272 #[derive(Clone, PartialEq, Hash)]
273 pub struct WatchedOutput {
274         /// First block where the transaction output may have been spent.
275         pub block_hash: Option<BlockHash>,
276
277         /// Outpoint identifying the transaction output.
278         pub outpoint: OutPoint,
279
280         /// Spending condition of the transaction output.
281         pub script_pubkey: Script,
282 }
283
284 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
285         fn block_connected(&self, block: &Block, height: u32) {
286                 (**self).block_connected(block, height);
287         }
288
289         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
290                 (**self).block_disconnected(header, height);
291         }
292 }
293
294 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
295 where
296         T::Target: Listen,
297         U::Target: Listen,
298 {
299         fn block_connected(&self, block: &Block, height: u32) {
300                 self.0.block_connected(block, height);
301                 self.1.block_connected(block, height);
302         }
303
304         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
305                 self.0.block_disconnected(header, height);
306                 self.1.block_disconnected(header, height);
307         }
308 }