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