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