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::sign::WriteableEcdsaChannelSigner;
21 use crate::chain::transaction::{OutPoint, TransactionData};
23 use crate::prelude::*;
25 pub mod chaininterface;
27 pub mod channelmonitor;
29 pub(crate) mod onchaintx;
30 pub(crate) mod package;
32 /// The best known block as identified by its hash and height.
33 #[derive(Clone, Copy, PartialEq, Eq)]
34 pub struct BestBlock {
35 block_hash: BlockHash,
40 /// Constructs a `BestBlock` that represents the genesis block at height 0 of the given
42 pub fn from_network(network: Network) -> Self {
44 block_hash: genesis_block(network).header.block_hash(),
49 /// Returns a `BestBlock` as identified by the given block hash and height.
50 pub fn new(block_hash: BlockHash, height: u32) -> Self {
51 BestBlock { block_hash, height }
54 /// Returns the best block hash.
55 pub fn block_hash(&self) -> BlockHash { self.block_hash }
57 /// Returns the best block height.
58 pub fn height(&self) -> u32 { self.height }
62 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
65 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
66 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
67 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
70 /// By using [`Listen::filtered_block_connected`] this interface supports clients fetching the
71 /// entire header chain and only blocks with matching transaction data using BIP 157 filters or
72 /// other similar filtering.
74 /// Notifies the listener that a block was added at the given height, with the transaction data
75 /// possibly filtered.
76 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
78 /// Notifies the listener that a block was added at the given height.
79 fn block_connected(&self, block: &Block, height: u32) {
80 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
81 self.filtered_block_connected(&block.header, &txdata, height);
84 /// Notifies the listener that a block was removed at the given height.
85 fn block_disconnected(&self, header: &BlockHeader, height: u32);
88 /// The `Confirm` trait is used to notify LDK when relevant transactions have been confirmed on
89 /// chain or unconfirmed during a chain reorganization.
91 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
92 /// [`Listen`]. For instance, an Electrum-based transaction sync implementation may implement
93 /// [`Filter`] to subscribe to relevant transactions and unspent outputs it should monitor for
94 /// on-chain activity. Then, it needs to notify LDK via this interface upon observing any changes
95 /// with reference to the confirmation status of the monitored objects.
98 /// The intended use is as follows:
99 /// - Call [`transactions_confirmed`] to notify LDK whenever any of the registered transactions or
100 /// outputs are, respectively, confirmed or spent on chain.
101 /// - Call [`transaction_unconfirmed`] to notify LDK whenever any transaction returned by
102 /// [`get_relevant_txids`] is no longer confirmed in the block with the given block hash.
103 /// - Call [`best_block_updated`] to notify LDK whenever a new chain tip becomes available.
107 /// Clients must call these methods in chain order. Specifically:
108 /// - Transactions which are confirmed in a particular block must be given before transactions
109 /// confirmed in a later block.
110 /// - Dependent transactions within the same block must be given in topological order, possibly in
112 /// - All unconfirmed transactions must be given after the original confirmations and before *any*
113 /// reconfirmations, i.e., [`transactions_confirmed`] and [`transaction_unconfirmed`] calls should
114 /// never be interleaved, but always conduced *en bloc*.
115 /// - Any reconfirmed transactions need to be explicitly unconfirmed before they are reconfirmed
116 /// in regard to the new block.
118 /// See individual method documentation for further details.
120 /// [`transactions_confirmed`]: Self::transactions_confirmed
121 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
122 /// [`best_block_updated`]: Self::best_block_updated
123 /// [`get_relevant_txids`]: Self::get_relevant_txids
125 /// Notifies LDK of transactions confirmed in a block with a given header and height.
127 /// Must be called for any transactions registered by [`Filter::register_tx`] or any
128 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
129 /// appearing in the same block do not need to be included in the same call; instead, multiple
130 /// calls with additional transactions may be made so long as they are made in [chain order].
132 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
133 /// in the event of a chain reorganization, it must not be called with a `header` that is no
134 /// longer in the chain as of the last call to [`best_block_updated`].
136 /// [chain order]: Confirm#order
137 /// [`best_block_updated`]: Self::best_block_updated
138 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
139 /// Notifies LDK of a transaction that is no longer confirmed as result of a chain reorganization.
141 /// Must be called for any transaction returned by [`get_relevant_txids`] if it has been
142 /// reorganized out of the best chain or if it is no longer confirmed in the block with the
143 /// given block hash. Once called, the given transaction will not be returned
144 /// by [`get_relevant_txids`], unless it has been reconfirmed via [`transactions_confirmed`].
146 /// [`get_relevant_txids`]: Self::get_relevant_txids
147 /// [`transactions_confirmed`]: Self::transactions_confirmed
148 fn transaction_unconfirmed(&self, txid: &Txid);
149 /// Notifies LDK of an update to the best header connected at the given height.
151 /// Must be called whenever a new chain tip becomes available. May be skipped for intermediary
153 fn best_block_updated(&self, header: &BlockHeader, height: u32);
154 /// Returns transactions that must be monitored for reorganization out of the chain along
155 /// with the hash of the block as part of which it had been previously confirmed.
157 /// Note that the returned `Option<BlockHash>` might be `None` for channels created with LDK
158 /// 0.0.112 and prior, in which case you need to manually track previous confirmations.
160 /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient
161 /// confirmations to be safe from a chain reorganization. Will not include any transactions
162 /// passed to [`transaction_unconfirmed`], unless later reconfirmed.
164 /// Must be called to determine the subset of transactions that must be monitored for
165 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
166 /// other interface methods. Thus, this is useful to determine which transactions must be
167 /// given to [`transaction_unconfirmed`].
169 /// If any of the returned transactions are confirmed in a block other than the one with the
170 /// given hash, they need to be unconfirmed and reconfirmed via [`transaction_unconfirmed`] and
171 /// [`transactions_confirmed`], respectively.
173 /// [`transactions_confirmed`]: Self::transactions_confirmed
174 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
175 fn get_relevant_txids(&self) -> Vec<(Txid, Option<BlockHash>)>;
178 /// An enum representing the status of a channel monitor update persistence.
180 /// Note that there is no error variant - any failure to persist a [`ChannelMonitor`] should be
181 /// retried indefinitely, the node shut down (as if we cannot update stored data we can't do much
182 /// of anything useful).
184 /// Note that channels should generally *not* be force-closed after a persistence failure.
185 /// Force-closing with the latest [`ChannelMonitorUpdate`] applied may result in a transaction
186 /// being broadcast which can only be spent by the latest [`ChannelMonitor`]! Thus, if the
187 /// latest [`ChannelMonitor`] is not durably persisted anywhere and exists only in memory, naively
188 /// calling [`ChannelManager::force_close_broadcasting_latest_txn`] *may result in loss of funds*!
190 /// [`ChannelManager::force_close_broadcasting_latest_txn`]: crate::ln::channelmanager::ChannelManager::force_close_broadcasting_latest_txn
191 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
192 pub enum ChannelMonitorUpdateStatus {
193 /// The update has been durably persisted and all copies of the relevant [`ChannelMonitor`]
194 /// have been updated.
196 /// This includes performing any `fsync()` calls required to ensure the update is guaranteed to
197 /// be available on restart even if the application crashes.
199 /// Indicates that the update will happen asynchronously in the background or that a transient
200 /// failure occurred which is being retried in the background and will eventually complete.
202 /// This will "freeze" a channel, preventing us from revoking old states or submitting a new
203 /// commitment transaction to the counterparty. Once the update(s) which are `InProgress` have
204 /// been completed, a [`MonitorEvent::Completed`] can be used to restore the channel to an
205 /// operational state.
207 /// Even when a channel has been "frozen", updates to the [`ChannelMonitor`] can continue to
208 /// occur (e.g. if an inbound HTLC which we forwarded was claimed upstream, resulting in us
209 /// attempting to claim it on this channel) and those updates must still be persisted.
211 /// No updates to the channel will be made which could invalidate other [`ChannelMonitor`]s
212 /// until a [`MonitorEvent::Completed`] is provided, even if you return no error on a later
213 /// monitor update for the same channel.
215 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
216 /// remote location (with local copies persisted immediately), it is anticipated that all
217 /// updates will return [`InProgress`] until the remote copies could be updated.
219 /// Note that while fully asynchronous persistence of [`ChannelMonitor`] data is generally
220 /// reliable, this feature is considered beta, and a handful of edge-cases remain. Until the
221 /// remaining cases are fixed, in rare cases, *using this feature may lead to funds loss*.
223 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
227 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
228 /// blocks are connected and disconnected.
230 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
231 /// responsible for maintaining a set of monitors such that they can be updated as channel state
232 /// changes. On each update, *all copies* of a [`ChannelMonitor`] must be updated and the update
233 /// persisted to disk to ensure that the latest [`ChannelMonitor`] state can be reloaded if the
234 /// application crashes.
236 /// See method documentation and [`ChannelMonitorUpdateStatus`] for specific requirements.
237 pub trait Watch<ChannelSigner: WriteableEcdsaChannelSigner> {
238 /// Watches a channel identified by `funding_txo` using `monitor`.
240 /// Implementations are responsible for watching the chain for the funding transaction along
241 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
242 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
244 /// A return of `Err(())` indicates that the channel should immediately be force-closed without
245 /// broadcasting the funding transaction.
247 /// If the given `funding_txo` has previously been registered via `watch_channel`, `Err(())`
248 /// must be returned.
250 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
251 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
252 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
253 fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()>;
255 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
257 /// Implementations must call [`ChannelMonitor::update_monitor`] with the given update. This
258 /// may fail (returning an `Err(())`), in which case this should return
259 /// [`ChannelMonitorUpdateStatus::InProgress`] (and the update should never complete). This
260 /// generally implies the channel has been closed (either by the funding outpoint being spent
261 /// on-chain or the [`ChannelMonitor`] having decided to do so and broadcasted a transaction),
262 /// and the [`ChannelManager`] state will be updated once it sees the funding spend on-chain.
264 /// If persistence fails, this should return [`ChannelMonitorUpdateStatus::InProgress`] and
265 /// the node should shut down immediately.
267 /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
268 fn update_channel(&self, funding_txo: OutPoint, update: &ChannelMonitorUpdate) -> ChannelMonitorUpdateStatus;
270 /// Returns any monitor events since the last call. Subsequent calls must only return new
273 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
274 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
277 /// For details on asynchronous [`ChannelMonitor`] updating and returning
278 /// [`MonitorEvent::Completed`] here, see [`ChannelMonitorUpdateStatus::InProgress`].
279 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>, Option<PublicKey>)>;
282 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
285 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
286 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
287 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
288 /// receiving full blocks from a chain source, any further filtering is unnecessary.
290 /// After an output has been registered, subsequent block retrievals from the chain source must not
291 /// exclude any transactions matching the new criteria nor any in-block descendants of such
294 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
295 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
296 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
297 /// invocation that has called the `Filter` must return [`InProgress`].
299 /// [`InProgress`]: ChannelMonitorUpdateStatus::InProgress
300 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
301 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
303 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
304 /// a spending condition.
305 fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
307 /// Registers interest in spends of a transaction output.
309 /// Note that this method might be called during processing of a new block. You therefore need
310 /// to ensure that also dependent output spents within an already connected block are correctly
311 /// handled, e.g., by re-scanning the block in question whenever new outputs have been
312 /// registered mid-processing.
313 fn register_output(&self, output: WatchedOutput);
316 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
318 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
319 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
320 /// [`Confirm::transactions_confirmed`].
322 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
323 /// may have been spent there. See [`Filter::register_output`] for details.
325 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
326 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
327 #[derive(Clone, PartialEq, Eq, Hash)]
328 pub struct WatchedOutput {
329 /// First block where the transaction output may have been spent.
330 pub block_hash: Option<BlockHash>,
332 /// Outpoint identifying the transaction output.
333 pub outpoint: OutPoint,
335 /// Spending condition of the transaction output.
336 pub script_pubkey: Script,
339 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
340 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
341 (**self).filtered_block_connected(header, txdata, height);
344 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
345 (**self).block_disconnected(header, height);
349 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
354 fn filtered_block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
355 self.0.filtered_block_connected(header, txdata, height);
356 self.1.filtered_block_connected(header, txdata, height);
359 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
360 self.0.block_disconnected(header, height);
361 self.1.block_disconnected(header, height);
365 /// A unique identifier to track each pending output claim within a [`ChannelMonitor`].
367 /// This is not exported to bindings users as we just use [u8; 32] directly.
368 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
369 pub struct ClaimId(pub [u8; 32]);