Merge pull request #1998 from tnull/2023-01-no-none-in-channel-relevant-txids
[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::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 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 LDK when relevant transactions have been confirmed on
111 /// chain or 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-based transaction sync implementation may implement
115 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
116 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
117 /// with reference to the confirmation status of the monitored objects.
118 ///
119 /// # Use
120 /// The intended use is as follows:
121 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
122 ///   outputs are, respectively, confirmed or spent on chain.
123 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
124 ///   [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
125 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
126 ///
127 /// # Order
128 ///
129 /// Clients must call these methods in chain order. Specifically:
130 /// - Transactions which are confirmed in a particular block must be given before transactions
131 ///   confirmed in a later block.
132 /// - Dependent transactions within the same block must be given in topological order, possibly in
133 ///   separate calls.
134 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
135 ///   reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
136 ///   never be interleaved, but always conduced *en bloc*.
137 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
138 ///   in regard to the new block.
139 ///
140 /// See individual method documentation for further details.
141 ///
142 /// [`transactions_confirmed`]: Self::transactions_confirmed
143 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
144 /// [`best_block_updated`]: Self::best_block_updated
145 /// [`get_relevant_txids`]: Self::get_relevant_txids
146 pub trait Confirm {
147         /// Notifies LDK of transactions confirmed in a block with a given header and height.
148         ///
149         /// Must be called for any transactions registered by [`Filter::register_tx`] or any
150         /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
151         /// appearing in the same block do not need to be included in the same call; instead, multiple
152         /// calls with additional transactions may be made so long as they are made in [chain order].
153         ///
154         /// May be called before or after [`best_block_updated`] for the corresponding block. However,
155         /// in the event of a chain reorganization, it must not be called with a `header` that is no
156         /// longer in the chain as of the last call to [`best_block_updated`].
157         ///
158         /// [chain order]: Confirm#order
159         /// [`best_block_updated`]: Self::best_block_updated
160         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
161         /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
162         ///
163         /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
164         /// reorganized out of the best chain or if it is no longer confirmed in the block with the
165         /// given block hash. Once called, the given transaction will not be returned
166         /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
167         ///
168         /// [`get_relevant_txids`]: Self::get_relevant_txids
169         /// [`transactions_confirmed`]: Self::transactions_confirmed
170         fn transaction_unconfirmed(&self, txid: &Txid);
171         /// Notifies LDK of an update to the best header connected at the given height.
172         ///
173         /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
174         /// blocks.
175         fn best_block_updated(&self, header: &BlockHeader, height: u32);
176         /// Returns transactions that must be monitored for reorganization out of the chain along
177         /// with the hash of the block as part of which it had been previously confirmed.
178         ///
179         /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
180         /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
181         ///
182         /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
183         /// confirmations to be safe from a chain reorganization. Will not include any transactions
184         /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
185         ///
186         /// Must be called to determine the subset of transactions that must be monitored for
187         /// reorganization. Will be idempotent between calls but may change as a result of calls to the
188         /// other interface methods. Thus, this is useful to determine which transactions must be
189         /// given to [`transaction_unconfirmed`].
190         ///
191         /// If any of the returned transactions are confirmed in a block other than the one with the
192         /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
193         /// [`transactions_confirmed`], respectively.
194         ///
195         /// [`transactions_confirmed`]: Self::transactions_confirmed
196         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
197         fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)>;
198 }
199
200 /// An enum representing the status of a channel monitor update persistence.
201 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
202 pub enum ChannelMonitorUpdateStatus {
203         /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
204         /// have been updated.
205         ///
206         /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
207         /// be available on restart even if the application crashes.
208         Completed,
209         /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
210         /// our state failed, but is expected to succeed at some point in the future).
211         ///
212         /// Such a failure will "freeze" a channel, preventing us from revoking old states or
213         /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
214         /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
215         /// channel to an operational state.
216         ///
217         /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
218         /// If you return this error you must ensure that it is written to disk safely before writing
219         /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
220         ///
221         /// Even when a channel has been "frozen", updates to the [`ChannelMonitor`] can continue to
222         /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
223         /// attempting to claim it on this channel) and those updates must still be persisted.
224         ///
225         /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
226         /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
227         /// monitor update for the same channel.
228         ///
229         /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
230         /// remote location (with local copies persisted immediately), it is anticipated that all
231         /// updates will return [`InProgress`] until the remote copies could be updated.
232         ///
233         /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
234         /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
235         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
236         InProgress,
237         /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
238         /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
239         ///
240         /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
241         /// our current commitment transaction. This avoids a dangerous case where a local disk failure
242         /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
243         /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
244         /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
245         /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
246         ///
247         /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
248         /// the data permanently, we really should broadcast immediately. If the data can be recovered
249         /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
250         /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
251         /// we do as long as blocks are connected).
252         ///
253         /// In order to broadcast the latest local commitment transaction, you'll need to call
254         /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
255         /// transactions once you've safely ensured no further channel updates can be generated by your
256         /// [`ChannelManager`].
257         ///
258         /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
259         /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
260         /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
261         /// commitment transaction) are allowed.
262         ///
263         /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
264         /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
265         /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
266         /// broadcasted later.
267         ///
268         /// In case of distributed watchtowers deployment, the new version must be written to disk, as
269         /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
270         /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
271         /// lagging behind on block processing.
272         ///
273         /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
274         /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
275         PermanentFailure,
276 }
277
278 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
279 /// blocks are connected and disconnected.
280 ///
281 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
282 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
283 /// channel state changes and HTLCs are resolved. See method documentation for specific
284 /// requirements.
285 ///
286 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
287 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
288 /// without taking any further action such as persisting the current state.
289 ///
290 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
291 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
292 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
293 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
294 /// multiple instances.
295 ///
296 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
297 pub trait Watch<ChannelSigner: WriteableEcdsaChannelSigner> {
298         /// Watches a channel identified by `funding_txo` using `monitor`.
299         ///
300         /// Implementations are responsible for watching the chain for the funding transaction along
301         /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
302         /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
303         ///
304         /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
305         /// the given `funding_txo` has previously been registered via `watch_channel`.
306         ///
307         /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
308         /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
309         /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
310         fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> ChannelMonitorUpdateStatus;
311
312         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
313         ///
314         /// Implementations must call [`update_monitor`] with the given update. See
315         /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
316         ///
317         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
318         fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus;
319
320         /// Returns any monitor events since the last call. Subsequent calls must only return new
321         /// events.
322         ///
323         /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
324         /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
325         /// to disk.
326         ///
327         /// For details on asynchronous [`ChannelMonitor`] updating and returning
328         /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
329         fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)>;
330 }
331
332 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
333 /// channels.
334 ///
335 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
336 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
337 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
338 /// receiving full blocks from a chain source, any further filtering is unnecessary.
339 ///
340 /// After an output has been registered, subsequent block retrievals from the chain source must not
341 /// exclude any transactions matching the new criteria nor any in-block descendants of such
342 /// transactions.
343 ///
344 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
345 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
346 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
347 /// invocation that has called the `Filter` must return [`InProgress`].
348 ///
349 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
350 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
351 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
352 pub trait Filter {
353         /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
354         /// a spending condition.
355         fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
356
357         /// Registers interest in spends of a transaction output.
358         ///
359         /// Note that this method might be called during processing of a new block. You therefore need
360         /// to ensure that also dependent output spents within an already connected block are correctly
361         /// handled, e.g., by re-scanning the block in question whenever new outputs have been
362         /// registered mid-processing.
363         fn register_output(&self, output: WatchedOutput);
364 }
365
366 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
367 ///
368 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
369 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
370 /// [`Confirm::transactions_confirmed`].
371 ///
372 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
373 /// may have been spent there. See [`Filter::register_output`] for details.
374 ///
375 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
376 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
377 #[derive(Clone, PartialEq, Eq, Hash)]
378 pub struct WatchedOutput {
379         /// First block where the transaction output may have been spent.
380         pub block_hash: Option<BlockHash>,
381
382         /// Outpoint identifying the transaction output.
383         pub outpoint: OutPoint,
384
385         /// Spending condition of the transaction output.
386         pub script_pubkey: Script,
387 }
388
389 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
390         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
391                 (**self).filtered_block_connected(header, txdata, height);
392         }
393
394         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
395                 (**self).block_disconnected(header, height);
396         }
397 }
398
399 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
400 where
401         T::Target: Listen,
402         U::Target: Listen,
403 {
404         fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
405                 self.0.filtered_block_connected(header, txdata, height);
406                 self.1.filtered_block_connected(header, txdata, height);
407         }
408
409         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
410                 self.0.block_disconnected(header, height);
411                 self.1.block_disconnected(header, height);
412         }
413 }