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