33d4826fef210b849b61818fd9ba241aad2a9971
[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::TxOut;
16 use bitcoin::hash_types::{BlockHash, Txid};
17 use bitcoin::network::constants::Network;
18 use bitcoin::secp256k1::PublicKey;
19
20 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
21 use crate::chain::keysinterface::Sign;
22 use crate::chain::transaction::{OutPoint, TransactionData};
23
24 use crate::prelude::*;
25
26 pub mod chaininterface;
27 pub mod chainmonitor;
28 pub mod channelmonitor;
29 pub mod transaction;
30 pub mod keysinterface;
31 pub(crate) mod onchaintx;
32 pub(crate) mod package;
33
34 /// The best known block as identified by its hash and height.
35 #[derive(Clone, Copy, PartialEq, Eq)]
36 pub struct BestBlock {
37         block_hash: BlockHash,
38         height: u32,
39 }
40
41 impl BestBlock {
42         /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
43         /// network.
44         pub fn from_genesis(network: Network) -> Self {
45                 BestBlock {
46                         block_hash: genesis_block(network).header.block_hash(),
47                         height: 0,
48                 }
49         }
50
51         /// Returns a `BestBlock` as identified by the given block hash and height.
52         pub fn new(block_hash: BlockHash, height: u32) -> Self {
53                 BestBlock { block_hash, height }
54         }
55
56         /// Returns the best block hash.
57         pub fn block_hash(&self) -> BlockHash { self.block_hash }
58
59         /// Returns the best block height.
60         pub fn height(&self) -> u32 { self.height }
61 }
62
63 /// An error when accessing the chain via [`Access`].
64 #[derive(Clone, Debug)]
65 pub enum AccessError {
66         /// The requested chain is unknown.
67         UnknownChain,
68
69         /// The requested transaction doesn't exist or hasn't confirmed.
70         UnknownTx,
71 }
72
73 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
74 /// UTXOs.
75 pub trait Access {
76         /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
77         /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
78         /// is unknown.
79         ///
80         /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id
81         fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
82 }
83
84 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
85 /// chain.
86 ///
87 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
88 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
89 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
90 /// when needed.
91 ///
92 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
93 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
94 /// other similar filtering.
95 pub trait Listen {
96         /// Notifies the listener that a block was added at the given height, with the transaction data
97         /// possibly filtered.
98         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
99
100         /// Notifies the listener that a block was added at the given height.
101         fn block_connected(&self, block: &Block, height: u32) {
102                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
103                 self.filtered_block_connected(&block.header, &txdata, height);
104         }
105
106         /// Notifies the listener that a block was removed at the given height.
107         fn block_disconnected(&self, header: &BlockHeader, height: u32);
108 }
109
110 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
111 /// unconfirmed during a chain reorganization.
112 ///
113 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
114 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
115 /// related to registered transactions and outputs. Upon notification, it would pass along the
116 /// matching transactions using this interface.
117 ///
118 /// # Use
119 ///
120 /// The intended use is as follows:
121 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
122 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
123 ///   that has been reorganized out of the chain.
124 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
125 ///
126 /// # Order
127 ///
128 /// Clients must call these methods in chain order. Specifically:
129 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
130 ///   block.
131 /// - Dependent transactions within the same block must be given in topological order, possibly in
132 ///   separate calls.
133 /// - Unconfirmed transactions must be given after the original confirmations and before any
134 ///   reconfirmation.
135 ///
136 /// See individual method documentation for further details.
137 ///
138 /// [`transactions_confirmed`]: Self::transactions_confirmed
139 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
140 /// [`best_block_updated`]: Self::best_block_updated
141 /// [`get_relevant_txids`]: Self::get_relevant_txids
142 pub trait Confirm {
143         /// Processes transactions confirmed in a block with a given header and height.
144         ///
145         /// Should be called for any transactions registered by [`Filter::register_tx`] or any
146         /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
147         /// appearing in the same block do not need to be included in the same call; instead, multiple
148         /// calls with additional transactions may be made so long as they are made in [chain order].
149         ///
150         /// May be called before or after [`best_block_updated`] for the corresponding block. However,
151         /// in the event of a chain reorganization, it must not be called with a `header` that is no
152         /// longer in the chain as of the last call to [`best_block_updated`].
153         ///
154         /// [chain order]: Confirm#order
155         /// [`best_block_updated`]: Self::best_block_updated
156         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
157
158         /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
159         ///
160         /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
161         /// reorganized out of the best chain. Once called, the given transaction will not be returned
162         /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
163         ///
164         /// [`get_relevant_txids`]: Self::get_relevant_txids
165         /// [`transactions_confirmed`]: Self::transactions_confirmed
166         fn transaction_unconfirmed(&self, txid: &Txid);
167
168         /// Processes an update to the best header connected at the given height.
169         ///
170         /// Should be called when a new header is available but may be skipped for intermediary blocks
171         /// if they become available at the same time.
172         fn best_block_updated(&self, header: &BlockHeader, height: u32);
173
174         /// Returns transactions that should be monitored for reorganization out of the chain along
175         /// with the hash of the block as part of which had been previously confirmed.
176         ///
177         /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
178         /// confirmations to be safe from a chain reorganization. Will not include any transactions
179         /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
180         ///
181         /// May be called to determine the subset of transactions that must still be monitored for
182         /// reorganization. Will be idempotent between calls but may change as a result of calls to the
183         /// other interface methods. Thus, this is useful to determine which transactions may need to be
184         /// given to [`transaction_unconfirmed`]. If any of the returned transactions are confirmed in
185         /// a block other than the one with the given hash, they need to be unconfirmed and reconfirmed
186         /// via [`transaction_unconfirmed`] and [`transactions_confirmed`], respectively.
187         ///
188         /// [`transactions_confirmed`]: Self::transactions_confirmed
189         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
190         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)>;
191 }
192
193 /// An enum representing the status of a channel monitor update persistence.
194 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
195 pub enum ChannelMonitorUpdateStatus {
196         /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
197         /// have been updated.
198         ///
199         /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
200         /// be available on restart even if the application crashes.
201         Completed,
202         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
203         /// our state failed, but is expected to succeed at some point in the future).
204         ///
205         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
206         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
207         /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
208         /// channel to an operational state.
209         ///
210         /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
211         /// If you return this error you must ensure that it is written to disk safely before writing
212         /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
213         ///
214         /// Even when a channel has been "frozen", updates to the [`ChannelMonitor`] can continue to
215         /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
216         /// attempting to claim it on this channel) and those updates must still be persisted.
217         ///
218         /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
219         /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
220         /// monitor update for the same channel.
221         ///
222         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
223         /// remote location (with local copies persisted immediately), it is anticipated that all
224         /// updates will return [`InProgress`] until the remote copies could be updated.
225         ///
226         /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
227         /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
228         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
229         InProgress,
230         /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
231         /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
232         ///
233         /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
234         /// our current commitment transaction. This avoids a dangerous case where a local disk failure
235         /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
236         /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
237         /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
238         /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
239         ///
240         /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
241         /// the data permanently, we really should broadcast immediately. If the data can be recovered
242         /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
243         /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
244         /// we do as long as blocks are connected).
245         ///
246         /// In order to broadcast the latest local commitment transaction, you'll need to call
247         /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
248         /// transactions once you've safely ensured no further channel updates can be generated by your
249         /// [`ChannelManager`].
250         ///
251         /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
252         /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
253         /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
254         /// commitment transaction) are allowed.
255         ///
256         /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
257         /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
258         /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
259         /// broadcasted later.
260         ///
261         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
262         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
263         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
264         /// lagging behind on block processing.
265         ///
266         /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
267         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
268         PermanentFailure,
269 }
270
271 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
272 /// blocks are connected and disconnected.
273 ///
274 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
275 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
276 /// channel state changes and HTLCs are resolved. See method documentation for specific
277 /// requirements.
278 ///
279 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
280 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
281 /// without taking any further action such as persisting the current state.
282 ///
283 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
284 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
285 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
286 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
287 /// multiple instances.
288 ///
289 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
290 pub trait Watch<ChannelSigner: Sign> {
291         /// Watches a channel identified by `funding_txo` using `monitor`.
292         ///
293         /// Implementations are responsible for watching the chain for the funding transaction along
294         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
295         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
296         ///
297         /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
298         /// the given `funding_txo` has previously been registered via `watch_channel`.
299         ///
300         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
301         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
302         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
303         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> ChannelMonitorUpdateStatus;
304
305         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
306         ///
307         /// Implementations must call [`update_monitor`] with the given update. See
308         /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
309         ///
310         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
311         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus;
312
313         /// Returns any monitor events since the last call. Subsequent calls must only return new
314         /// events.
315         ///
316         /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
317         /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
318         /// to disk.
319         ///
320         /// For details on asynchronous [`ChannelMonitor`] updating and returning
321         /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
322         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)>;
323 }
324
325 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
326 /// channels.
327 ///
328 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
329 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
330 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
331 /// receiving full blocks from a chain source, any further filtering is unnecessary.
332 ///
333 /// After an output has been registered, subsequent block retrievals from the chain source must not
334 /// exclude any transactions matching the new criteria nor any in-block descendants of such
335 /// transactions.
336 ///
337 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
338 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
339 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
340 /// invocation that has called the `Filter` must return [`InProgress`].
341 ///
342 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
343 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
344 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
345 pub trait Filter {
346         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
347         /// a spending condition.
348         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
349
350         /// Registers interest in spends of a transaction output.
351         ///
352         /// Note that this method might be called during processing of a new block. You therefore need
353         /// to ensure that also dependent output spents within an already connected block are correctly
354         /// handled, e.g., by re-scanning the block in question whenever new outputs have been
355         /// registered mid-processing.
356         fn register_output(&self, output: WatchedOutput);
357 }
358
359 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
360 ///
361 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
362 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
363 /// [`Confirm::transactions_confirmed`].
364 ///
365 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
366 /// may have been spent there. See [`Filter::register_output`] for details.
367 ///
368 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
369 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
370 #[derive(Clone, PartialEq, Eq, Hash)]
371 pub struct WatchedOutput {
372         /// First block where the transaction output may have been spent.
373         pub block_hash: Option<BlockHash>,
374
375         /// Outpoint identifying the transaction output.
376         pub outpoint: OutPoint,
377
378         /// Spending condition of the transaction output.
379         pub script_pubkey: Script,
380 }
381
382 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
383         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
384                 (**self).filtered_block_connected(header, txdata, height);
385         }
386
387         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
388                 (**self).block_disconnected(header, height);
389         }
390 }
391
392 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
393 where
394         T::Target: Listen,
395         U::Target: Listen,
396 {
397         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
398                 self.0.filtered_block_connected(header, txdata, height);
399                 self.1.filtered_block_connected(header, txdata, height);
400         }
401
402         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
403                 self.0.block_disconnected(header, height);
404                 self.1.block_disconnected(header, height);
405         }
406 }