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