1 // This file is Copyright its original authors, visible in version control
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
10 //! Structs and traits which allow other parts of rust-lightning to interact with the blockchain.
12 use bitcoin::blockdata::block::{Block, BlockHeader};
13 use bitcoin::blockdata::constants::genesis_block;
14 use bitcoin::blockdata::script::Script;
15 use bitcoin::hash_types::{BlockHash, Txid};
16 use bitcoin::network::constants::Network;
17 use bitcoin::secp256k1::PublicKey;
19 use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
20 use crate::chain::keysinterface::WriteableEcdsaChannelSigner;
21 use crate::chain::transaction::{OutPoint, TransactionData};
23 use crate::prelude::*;
25 pub mod chaininterface;
27 pub mod channelmonitor;
29 pub mod keysinterface;
30 pub(crate) mod onchaintx;
31 pub(crate) mod package;
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,
41 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
43 pub fn from_network(network: Network) -> Self {
45 block_hash: genesis_block(network).header.block_hash(),
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 }
55 /// Returns the best block hash.
56 pub fn block_hash(&self) -> BlockHash { self.block_hash }
58 /// Returns the best block height.
59 pub fn height(&self) -> u32 { self.height }
63 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
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
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.
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: &BlockHeader, txdata: &TransactionData, height: u32);
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);
85 /// Notifies the listener that a block was removed at the given height.
86 fn block_disconnected(&self, header: &BlockHeader, height: u32);
89 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
90 /// chain or unconfirmed during a chain reorganization.
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.
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.
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
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.
119 /// See individual method documentation for further details.
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
126 /// Notifies LDK of transactions confirmed in a block with a given header and height.
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].
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`].
137 /// [chain order]: Confirm#order
138 /// [`best_block_updated`]: Self::best_block_updated
139 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
140 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
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`].
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.
152 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
154 fn best_block_updated(&self, header: &BlockHeader, height: u32);
155 /// Returns transactions that must be monitored for reorganization out of the chain along
156 /// with the hash of the block as part of which it had been previously confirmed.
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.
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.
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`].
170 /// If any of the returned transactions are confirmed in a block other than the one with the
171 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
172 /// [`transactions_confirmed`], respectively.
174 /// [`transactions_confirmed`]: Self::transactions_confirmed
175 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
176 fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)>;
179 /// An enum representing the status of a channel monitor update persistence.
180 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
181 pub enum ChannelMonitorUpdateStatus {
182 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
183 /// have been updated.
185 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
186 /// be available on restart even if the application crashes.
188 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
189 /// our state failed, but is expected to succeed at some point in the future).
191 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
192 /// submitting new commitment transactions to the counterparty. Once the update(s) which failed
193 /// have been successfully applied, a [`MonitorEvent::Completed`] can be used to restore the
194 /// channel to an operational state.
196 /// Note that a given [`ChannelManager`] will *never* re-generate a [`ChannelMonitorUpdate`].
197 /// If you return this error you must ensure that it is written to disk safely before writing
198 /// the latest [`ChannelManager`] state, or you should return [`PermanentFailure`] instead.
200 /// Even when a channel has been "frozen", updates to the [`ChannelMonitor`] can continue to
201 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
202 /// attempting to claim it on this channel) and those updates must still be persisted.
204 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
205 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
206 /// monitor update for the same channel.
208 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
209 /// remote location (with local copies persisted immediately), it is anticipated that all
210 /// updates will return [`InProgress`] until the remote copies could be updated.
212 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
213 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
214 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
216 /// Used to indicate no further channel monitor updates will be allowed (likely a disk failure
217 /// or a remote copy of this [`ChannelMonitor`] is no longer reachable and thus not updatable).
219 /// When this is returned, [`ChannelManager`] will force-close the channel but *not* broadcast
220 /// our current commitment transaction. This avoids a dangerous case where a local disk failure
221 /// (e.g. the Linux-default remounting of the disk as read-only) causes [`PermanentFailure`]s
222 /// for all monitor updates. If we were to broadcast our latest commitment transaction and then
223 /// restart, we could end up reading a previous [`ChannelMonitor`] and [`ChannelManager`],
224 /// revoking our now-broadcasted state before seeing it confirm and losing all our funds.
226 /// Note that this is somewhat of a tradeoff - if the disk is really gone and we may have lost
227 /// the data permanently, we really should broadcast immediately. If the data can be recovered
228 /// with manual intervention, we'd rather close the channel, rejecting future updates to it,
229 /// and broadcast the latest state only if we have HTLCs to claim which are timing out (which
230 /// we do as long as blocks are connected).
232 /// In order to broadcast the latest local commitment transaction, you'll need to call
233 /// [`ChannelMonitor::get_latest_holder_commitment_txn`] and broadcast the resulting
234 /// transactions once you've safely ensured no further channel updates can be generated by your
235 /// [`ChannelManager`].
237 /// Note that at least one final [`ChannelMonitorUpdate`] may still be provided, which must
238 /// still be processed by a running [`ChannelMonitor`]. This final update will mark the
239 /// [`ChannelMonitor`] as finalized, ensuring no further updates (e.g. revocation of the latest
240 /// commitment transaction) are allowed.
242 /// Note that even if you return a [`PermanentFailure`] due to unavailability of secondary
243 /// [`ChannelMonitor`] copies, you should still make an attempt to store the update where
244 /// possible to ensure you can claim HTLC outputs on the latest commitment transaction
245 /// broadcasted later.
247 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
248 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
249 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
250 /// lagging behind on block processing.
252 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
253 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
257 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
258 /// blocks are connected and disconnected.
260 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
261 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
262 /// channel state changes and HTLCs are resolved. See method documentation for specific
265 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
266 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
267 /// without taking any further action such as persisting the current state.
269 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
270 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
271 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
272 /// funds in the channel. See [`ChannelMonitorUpdateStatus`] for more details about how to handle
273 /// multiple instances.
275 /// [`PermanentFailure`]: ChannelMonitorUpdateStatus::PermanentFailure
276 pub trait Watch<ChannelSigner: WriteableEcdsaChannelSigner> {
277 /// Watches a channel identified by `funding_txo` using `monitor`.
279 /// Implementations are responsible for watching the chain for the funding transaction along
280 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
281 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
283 /// Note: this interface MUST error with [`ChannelMonitorUpdateStatus::PermanentFailure`] if
284 /// the given `funding_txo` has previously been registered via `watch_channel`.
286 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
287 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
288 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
289 fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> ChannelMonitorUpdateStatus;
291 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
293 /// Implementations must call [`update_monitor`] with the given update. See
294 /// [`ChannelMonitorUpdateStatus`] for invariants around returning an error.
296 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
297 fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus;
299 /// Returns any monitor events since the last call. Subsequent calls must only return new
302 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
303 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
306 /// For details on asynchronous [`ChannelMonitor`] updating and returning
307 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
308 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)>;
311 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
314 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
315 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
316 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
317 /// receiving full blocks from a chain source, any further filtering is unnecessary.
319 /// After an output has been registered, subsequent block retrievals from the chain source must not
320 /// exclude any transactions matching the new criteria nor any in-block descendants of such
323 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
324 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
325 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
326 /// invocation that has called the `Filter` must return [`InProgress`].
328 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
329 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
330 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
332 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
333 /// a spending condition.
334 fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
336 /// Registers interest in spends of a transaction output.
338 /// Note that this method might be called during processing of a new block. You therefore need
339 /// to ensure that also dependent output spents within an already connected block are correctly
340 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
341 /// registered mid-processing.
342 fn register_output(&self, output: WatchedOutput);
345 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
347 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
348 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
349 /// [`Confirm::transactions_confirmed`].
351 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
352 /// may have been spent there. See [`Filter::register_output`] for details.
354 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
355 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
356 #[derive(Clone, PartialEq, Eq, Hash)]
357 pub struct WatchedOutput {
358 /// First block where the transaction output may have been spent.
359 pub block_hash: Option<BlockHash>,
361 /// Outpoint identifying the transaction output.
362 pub outpoint: OutPoint,
364 /// Spending condition of the transaction output.
365 pub script_pubkey: Script,
368 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
369 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
370 (**self).filtered_block_connected(header, txdata, height);
373 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
374 (**self).block_disconnected(header, height);
378 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
383 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
384 self.0.filtered_block_connected(header, txdata, height);
385 self.1.filtered_block_connected(header, txdata, height);
388 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
389 self.0.block_disconnected(header, height);
390 self.1.block_disconnected(header, height);