356520b5cba86e647acdec77fd0cb86b683e7d58
[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, Header};
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::blockdata::script::{Script, ScriptBuf};
15 use bitcoin::hash_types::{BlockHash, Txid};
16 use bitcoin::network::constants::Network;
17 use bitcoin::secp256k1::PublicKey;
18
19 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
20 use crate::ln::ChannelId;
21 use crate::sign::ecdsa::WriteableEcdsaChannelSigner;
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(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, Debug, Hash, PartialEq, Eq)]
35 pub struct BestBlock {
36         /// The block's hash
37         pub block_hash: BlockHash,
38         /// The height at which the block was confirmed.
39         pub height: u32,
40 }
41
42 impl BestBlock {
43         /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
44         /// network.
45         pub fn from_network(network: Network) -> Self {
46                 BestBlock {
47                         block_hash: genesis_block(network).header.block_hash(),
48                         height: 0,
49                 }
50         }
51
52         /// Returns a `BestBlock` as identified by the given block hash and height.
53         pub fn new(block_hash: BlockHash, height: u32) -> Self {
54                 BestBlock { block_hash, height }
55         }
56 }
57
58
59 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
60 /// chain.
61 ///
62 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
63 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
64 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
65 /// when needed.
66 ///
67 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
68 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
69 /// other similar filtering.
70 pub trait Listen {
71         /// Notifies the listener that a block was added at the given height, with the transaction data
72         /// possibly filtered.
73         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32);
74
75         /// Notifies the listener that a block was added at the given height.
76         fn block_connected(&self, block: &Block, height: u32) {
77                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
78                 self.filtered_block_connected(&block.header, &txdata, height);
79         }
80
81         /// Notifies the listener that a block was removed at the given height.
82         fn block_disconnected(&self, header: &Header, height: u32);
83 }
84
85 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
86 /// chain or unconfirmed during a chain reorganization.
87 ///
88 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
89 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
90 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
91 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
92 /// with reference to the confirmation status of the monitored objects.
93 ///
94 /// # Use
95 /// The intended use is as follows:
96 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
97 ///   outputs are, respectively, confirmed or spent on chain.
98 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
99 ///   [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
100 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
101 ///
102 /// # Order
103 ///
104 /// Clients must call these methods in chain order. Specifically:
105 /// - Transactions which are confirmed in a particular block must be given before transactions
106 ///   confirmed in a later block.
107 /// - Dependent transactions within the same block must be given in topological order, possibly in
108 ///   separate calls.
109 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
110 ///   reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
111 ///   never be interleaved, but always conduced *en bloc*.
112 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
113 ///   in regard to the new block.
114 ///
115 /// See individual method documentation for further details.
116 ///
117 /// [`transactions_confirmed`]: Self::transactions_confirmed
118 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
119 /// [`best_block_updated`]: Self::best_block_updated
120 /// [`get_relevant_txids`]: Self::get_relevant_txids
121 pub trait Confirm {
122         /// Notifies LDK of transactions confirmed in a block with a given header and height.
123         ///
124         /// Must be called for any transactions registered by [`Filter::register_tx`] or any
125         /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
126         /// appearing in the same block do not need to be included in the same call; instead, multiple
127         /// calls with additional transactions may be made so long as they are made in [chain order].
128         ///
129         /// May be called before or after [`best_block_updated`] for the corresponding block. However,
130         /// in the event of a chain reorganization, it must not be called with a `header` that is no
131         /// longer in the chain as of the last call to [`best_block_updated`].
132         ///
133         /// [chain order]: Confirm#order
134         /// [`best_block_updated`]: Self::best_block_updated
135         fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32);
136         /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
137         ///
138         /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
139         /// reorganized out of the best chain or if it is no longer confirmed in the block with the
140         /// given block hash. Once called, the given transaction will not be returned
141         /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
142         ///
143         /// [`get_relevant_txids`]: Self::get_relevant_txids
144         /// [`transactions_confirmed`]: Self::transactions_confirmed
145         fn transaction_unconfirmed(&self, txid: &Txid);
146         /// Notifies LDK of an update to the best header connected at the given height.
147         ///
148         /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
149         /// blocks.
150         fn best_block_updated(&self, header: &Header, height: u32);
151         /// Returns transactions that must be monitored for reorganization out of the chain along
152         /// with the height and the hash of the block as part of which it had been previously confirmed.
153         ///
154         /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
155         /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
156         ///
157         /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
158         /// confirmations to be safe from a chain reorganization. Will not include any transactions
159         /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
160         ///
161         /// Must be called to determine the subset of transactions that must be monitored for
162         /// reorganization. Will be idempotent between calls but may change as a result of calls to the
163         /// other interface methods. Thus, this is useful to determine which transactions must be
164         /// given to [`transaction_unconfirmed`].
165         ///
166         /// If any of the returned transactions are confirmed in a block other than the one with the
167         /// given hash at the given height, they need to be unconfirmed and reconfirmed via
168         /// [`transaction_unconfirmed`] and [`transactions_confirmed`], respectively.
169         ///
170         /// [`transactions_confirmed`]: Self::transactions_confirmed
171         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
172         fn get_relevant_txids(&self) -> Vec<(Txid, u32, Option<BlockHash>)>;
173 }
174
175 /// An enum representing the status of a channel monitor update persistence.
176 ///
177 /// These are generally used as the return value for an implementation of [`Persist`] which is used
178 /// as the storage layer for a [`ChainMonitor`]. See the docs on [`Persist`] for a high-level
179 /// explanation of how to handle different cases.
180 ///
181 /// While `UnrecoverableError` is provided as a failure variant, it is not truly "handled" on the
182 /// calling side, and generally results in an immediate panic. For those who prefer to avoid
183 /// panics, `InProgress` can be used and you can retry the update operation in the background or
184 /// shut down cleanly.
185 ///
186 /// Note that channels should generally *not* be force-closed after a persistence failure.
187 /// Force-closing with the latest [`ChannelMonitorUpdate`] applied may result in a transaction
188 /// being broadcast which can only be spent by the latest [`ChannelMonitor`]! Thus, if the
189 /// latest [`ChannelMonitor`] is not durably persisted anywhere and exists only in memory, naively
190 /// calling [`ChannelManager::force_close_broadcasting_latest_txn`] *may result in loss of funds*!
191 ///
192 /// [`Persist`]: chainmonitor::Persist
193 /// [`ChainMonitor`]: chainmonitor::ChainMonitor
194 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
195 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
196 pub enum ChannelMonitorUpdateStatus {
197         /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
198         /// have been updated.
199         ///
200         /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
201         /// be available on restart even if the application crashes.
202         Completed,
203         /// Indicates that the update will happen asynchronously in the background or that a transient
204         /// failure occurred which is being retried in the background and will eventually complete.
205         ///
206         /// This will "freeze" a channel, preventing us from revoking old states or submitting a new
207         /// commitment transaction to the counterparty. Once the update(s) which are `InProgress` have
208         /// been completed, a [`MonitorEvent::Completed`] can be used to restore the channel to an
209         /// operational state.
210         ///
211         /// Even when a channel has been "frozen", updates to the [`ChannelMonitor`] can continue to
212         /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
213         /// attempting to claim it on this channel) and those updates must still be persisted.
214         ///
215         /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
216         /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
217         /// monitor update for the same channel.
218         ///
219         /// For deployments where a copy of [`ChannelMonitor`]s and other local state are backed up in
220         /// a remote location (with local copies persisted immediately), it is anticipated that all
221         /// updates will return [`InProgress`] until the remote copies could be updated.
222         ///
223         /// Note that while fully asynchronous persistence of [`ChannelMonitor`] data is generally
224         /// reliable, this feature is considered beta, and a handful of edge-cases remain. Until the
225         /// remaining cases are fixed, in rare cases, *using this feature may lead to funds loss*.
226         ///
227         /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
228         InProgress,
229         /// Indicates that an update has failed and will not complete at any point in the future.
230         ///
231         /// Currently returning this variant will cause LDK to immediately panic to encourage immediate
232         /// shutdown. In the future this may be updated to disconnect peers and refuse to continue
233         /// normal operation without a panic.
234         ///
235         /// Applications which wish to perform an orderly shutdown after failure should consider
236         /// returning [`InProgress`] instead and simply shut down without ever marking the update
237         /// complete.
238         ///
239         /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
240         UnrecoverableError,
241 }
242
243 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
244 /// blocks are connected and disconnected.
245 ///
246 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
247 /// responsible for maintaining a set of monitors such that they can be updated as channel state
248 /// changes. On each update, *all copies* of a [`ChannelMonitor`] must be updated and the update
249 /// persisted to disk to ensure that the latest [`ChannelMonitor`] state can be reloaded if the
250 /// application crashes.
251 ///
252 /// See method documentation and [`ChannelMonitorUpdateStatus`] for specific requirements.
253 pub trait Watch<ChannelSigner: WriteableEcdsaChannelSigner> {
254         /// Watches a channel identified by `funding_txo` using `monitor`.
255         ///
256         /// Implementations are responsible for watching the chain for the funding transaction along
257         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
258         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
259         ///
260         /// A return of `Err(())` indicates that the channel should immediately be force-closed without
261         /// broadcasting the funding transaction.
262         ///
263         /// If the given `funding_txo` has previously been registered via `watch_channel`, `Err(())`
264         /// must be returned.
265         ///
266         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
267         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
268         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
269         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()>;
270
271         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
272         ///
273         /// Implementations must call [`ChannelMonitor::update_monitor`] with the given update. This
274         /// may fail (returning an `Err(())`), in which case this should return
275         /// [`ChannelMonitorUpdateStatus::InProgress`] (and the update should never complete). This
276         /// generally implies the channel has been closed (either by the funding outpoint being spent
277         /// on-chain or the [`ChannelMonitor`] having decided to do so and broadcasted a transaction),
278         /// and the [`ChannelManager`] state will be updated once it sees the funding spend on-chain.
279         ///
280         /// In general, persistence failures should be retried after returning
281         /// [`ChannelMonitorUpdateStatus::InProgress`] and eventually complete. If a failure truly
282         /// cannot be retried, the node should shut down immediately after returning
283         /// [`ChannelMonitorUpdateStatus::UnrecoverableError`], see its documentation for more info.
284         ///
285         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
286         fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus;
287
288         /// Returns any monitor events since the last call. Subsequent calls must only return new
289         /// events.
290         ///
291         /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
292         /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
293         /// to disk.
294         ///
295         /// For details on asynchronous [`ChannelMonitor`] updating and returning
296         /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
297         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, Option<PublicKey>)>;
298 }
299
300 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
301 /// channels.
302 ///
303 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
304 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
305 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
306 /// receiving full blocks from a chain source, any further filtering is unnecessary.
307 ///
308 /// After an output has been registered, subsequent block retrievals from the chain source must not
309 /// exclude any transactions matching the new criteria nor any in-block descendants of such
310 /// transactions.
311 ///
312 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
313 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
314 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
315 /// invocation that has called the `Filter` must return [`InProgress`].
316 ///
317 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
318 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
319 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
320 pub trait Filter {
321         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
322         /// a spending condition.
323         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
324
325         /// Registers interest in spends of a transaction output.
326         ///
327         /// Note that this method might be called during processing of a new block. You therefore need
328         /// to ensure that also dependent output spents within an already connected block are correctly
329         /// handled, e.g., by re-scanning the block in question whenever new outputs have been
330         /// registered mid-processing.
331         fn register_output(&self, output: WatchedOutput);
332 }
333
334 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
335 ///
336 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
337 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
338 /// [`Confirm::transactions_confirmed`].
339 ///
340 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
341 /// may have been spent there. See [`Filter::register_output`] for details.
342 ///
343 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
344 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
345 #[derive(Clone, PartialEq, Eq, Hash)]
346 pub struct WatchedOutput {
347         /// First block where the transaction output may have been spent.
348         pub block_hash: Option<BlockHash>,
349
350         /// Outpoint identifying the transaction output.
351         pub outpoint: OutPoint,
352
353         /// Spending condition of the transaction output.
354         pub script_pubkey: ScriptBuf,
355 }
356
357 impl<T: Listen> Listen for dyn core::ops::Deref<Target = T> {
358         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
359                 (**self).filtered_block_connected(header, txdata, height);
360         }
361
362         fn block_disconnected(&self, header: &Header, height: u32) {
363                 (**self).block_disconnected(header, height);
364         }
365 }
366
367 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
368 where
369         T::Target: Listen,
370         U::Target: Listen,
371 {
372         fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
373                 self.0.filtered_block_connected(header, txdata, height);
374                 self.1.filtered_block_connected(header, txdata, height);
375         }
376
377         fn block_disconnected(&self, header: &Header, height: u32) {
378                 self.0.block_disconnected(header, height);
379                 self.1.block_disconnected(header, height);
380         }
381 }
382
383 /// A unique identifier to track each pending output claim within a [`ChannelMonitor`].
384 ///
385 /// This is not exported to bindings users as we just use [u8; 32] directly.
386 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
387 pub struct ClaimId(pub [u8; 32]);