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::blockdata::transaction::{Transaction, TxOut};
16 use bitcoin::hash_types::{BlockHash, Txid};
17 use bitcoin::network::constants::Network;
19 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, MonitorEvent};
20 use chain::keysinterface::Sign;
21 use chain::transaction::{OutPoint, TransactionData};
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)]
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_genesis(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 }
62 /// An error when accessing the chain via [`Access`].
64 pub enum AccessError {
65 /// The requested chain is unknown.
68 /// The requested transaction doesn't exist or hasn't confirmed.
72 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
75 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
76 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
79 /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
80 fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
83 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
86 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
87 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
88 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
91 /// Notifies the listener that a block was added at the given height.
92 fn block_connected(&self, block: &Block, height: u32);
94 /// Notifies the listener that a block was removed at the given height.
95 fn block_disconnected(&self, header: &BlockHeader, height: u32);
98 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
99 /// unconfirmed during a chain reorganization.
101 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
102 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
103 /// related to registered transactions and outputs. Upon notification, it would pass along the
104 /// matching transactions using this interface.
108 /// The intended use is as follows:
109 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
110 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
111 /// that has been reorganized out of the chain.
112 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
116 /// Clients must call these methods in chain order. Specifically:
117 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
119 /// - Dependent transactions within the same block must be given in topological order, possibly in
121 /// - Unconfirmed transactions must be given after the original confirmations and before any
124 /// See individual method documentation for further details.
126 /// [`transactions_confirmed`]: Self::transactions_confirmed
127 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
128 /// [`best_block_updated`]: Self::best_block_updated
129 /// [`get_relevant_txids`]: Self::get_relevant_txids
131 /// Processes transactions confirmed in a block with a given header and height.
133 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
134 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
135 /// appearing in the same block do not need to be included in the same call; instead, multiple
136 /// calls with additional transactions may be made so long as they are made in [chain order].
138 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
139 /// in the event of a chain reorganization, it must not be called with a `header` that is no
140 /// longer in the chain as of the last call to [`best_block_updated`].
142 /// [chain order]: Confirm#Order
143 /// [`best_block_updated`]: Self::best_block_updated
144 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
146 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
148 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
149 /// reorganized out of the best chain. Once called, the given transaction should not be returned
150 /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
152 /// [`get_relevant_txids`]: Self::get_relevant_txids
153 /// [`transactions_confirmed`]: Self::transactions_confirmed
154 fn transaction_unconfirmed(&self, txid: &Txid);
156 /// Processes an update to the best header connected at the given height.
158 /// Should be called when a new header is available but may be skipped for intermediary blocks
159 /// if they become available at the same time.
160 fn best_block_updated(&self, header: &BlockHeader, height: u32);
162 /// Returns transactions that should be monitored for reorganization out of the chain.
164 /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
165 /// confirmations to be safe from a chain reorganization. Should not include any transactions
166 /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
168 /// May be called to determine the subset of transactions that must still 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 may need to be
171 /// given to [`transaction_unconfirmed`].
173 /// [`transactions_confirmed`]: Self::transactions_confirmed
174 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
175 fn get_relevant_txids(&self) -> Vec<Txid>;
178 /// An error enum representing a failure to persist a channel monitor update.
179 #[derive(Clone, Copy, Debug, PartialEq)]
180 pub enum ChannelMonitorUpdateErr {
181 /// Used to indicate a temporary failure (eg connection to a watchtower or remote backup of
182 /// our state failed, but is expected to succeed at some point in the future).
184 /// Such a failure will "freeze" a channel, preventing us from revoking old states or
185 /// submitting new commitment transactions to the counterparty. Once the update(s) that failed
186 /// have been successfully applied, a [`MonitorEvent::UpdateCompleted`] event should be returned
187 /// via [`Watch::release_pending_monitor_events`] which will then restore the channel to an
188 /// operational state.
190 /// Note that a given ChannelManager will *never* re-generate a given ChannelMonitorUpdate. If
191 /// you return a TemporaryFailure you must ensure that it is written to disk safely before
192 /// writing out the latest ChannelManager state.
194 /// Even when a channel has been "frozen" updates to the ChannelMonitor can continue to occur
195 /// (eg if an inbound HTLC which we forwarded was claimed upstream resulting in us attempting
196 /// to claim it on this channel) and those updates must be applied wherever they can be. At
197 /// least one such updated ChannelMonitor must be persisted otherwise PermanentFailure should
198 /// be returned to get things on-chain ASAP using only the in-memory copy. Obviously updates to
199 /// the channel which would invalidate previous ChannelMonitors are not made when a channel has
202 /// Note that even if updates made after TemporaryFailure succeed you must still provide a
203 /// [`MonitorEvent::UpdateCompleted`] to ensure you have the latest monitor and re-enable
204 /// normal channel operation. Note that this is normally generated through a call to
205 /// [`ChainMonitor::channel_monitor_updated`].
207 /// Note that the update being processed here will not be replayed for you when you return a
208 /// [`MonitorEvent::UpdateCompleted`] event via [`Watch::release_pending_monitor_events`], so
209 /// you must store the update itself on your own local disk prior to returning a
210 /// TemporaryFailure. You may, of course, employ a journaling approach, storing only the
211 /// ChannelMonitorUpdate on disk without updating the monitor itself, replaying the journal at
214 /// For deployments where a copy of ChannelMonitors and other local state are backed up in a
215 /// remote location (with local copies persisted immediately), it is anticipated that all
216 /// updates will return TemporaryFailure until the remote copies could be updated.
218 /// [`ChainMonitor::channel_monitor_updated`]: chainmonitor::ChainMonitor::channel_monitor_updated
220 /// Used to indicate no further channel monitor updates will be allowed (eg we've moved on to a
221 /// different watchtower and cannot update with all watchtowers that were previously informed
222 /// of this channel).
224 /// At reception of this error, ChannelManager will force-close the channel and return at
225 /// least a final ChannelMonitorUpdate::ChannelForceClosed which must be delivered to at
226 /// least one ChannelMonitor copy. Revocation secret MUST NOT be released and offchain channel
227 /// update must be rejected.
229 /// This failure may also signal a failure to update the local persisted copy of one of
230 /// the channel monitor instance.
232 /// Note that even when you fail a holder commitment transaction update, you must store the
233 /// update to ensure you can claim from it in case of a duplicate copy of this ChannelMonitor
234 /// broadcasts it (e.g distributed channel-monitor deployment)
236 /// In case of distributed watchtowers deployment, the new version must be written to disk, as
237 /// state may have been stored but rejected due to a block forcing a commitment broadcast. This
238 /// storage is used to claim outputs of rejected state confirmed onchain by another watchtower,
239 /// lagging behind on block processing.
243 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
244 /// blocks are connected and disconnected.
246 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
247 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
248 /// channel state changes and HTLCs are resolved. See method documentation for specific
251 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
252 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
253 /// without taking any further action such as persisting the current state.
255 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
256 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
257 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
258 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
259 /// multiple instances.
261 /// [`PermanentFailure`]: ChannelMonitorUpdateErr::PermanentFailure
262 pub trait Watch<ChannelSigner: Sign> {
263 /// Watches a channel identified by `funding_txo` using `monitor`.
265 /// Implementations are responsible for watching the chain for the funding transaction along
266 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
267 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
269 /// Note: this interface MUST error with `ChannelMonitorUpdateErr::PermanentFailure` if
270 /// the given `funding_txo` has previously been registered via `watch_channel`.
272 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
273 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
274 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
275 fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
277 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
279 /// Implementations must call [`update_monitor`] with the given update. See
280 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
282 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
283 fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
285 /// Returns any monitor events since the last call. Subsequent calls must only return new
288 /// Note that after any block- or transaction-connection calls to a [`ChannelMonitor`], no
289 /// further events may be returned here until the [`ChannelMonitor`] has been fully persisted
292 /// For details on asynchronous [`ChannelMonitor`] updating and returning
293 /// [`MonitorEvent::UpdateCompleted`] here, see [`ChannelMonitorUpdateErr::TemporaryFailure`].
294 fn release_pending_monitor_events(&self) -> Vec<(OutPoint, Vec<MonitorEvent>)>;
297 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
300 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
301 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
302 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
303 /// receiving full blocks from a chain source, any further filtering is unnecessary.
305 /// After an output has been registered, subsequent block retrievals from the chain source must not
306 /// exclude any transactions matching the new criteria nor any in-block descendants of such
309 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
310 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
311 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
312 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
314 /// [`TemporaryFailure`]: ChannelMonitorUpdateErr::TemporaryFailure
315 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
316 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
318 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
319 /// a spending condition.
320 fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
322 /// Registers interest in spends of a transaction output.
324 /// Optionally, when `output.block_hash` is set, should return any transaction spending the
325 /// output that is found in the corresponding block along with its index.
327 /// This return value is useful for Electrum clients in order to supply in-block descendant
328 /// transactions which otherwise were not included. This is not necessary for other clients if
329 /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
331 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
334 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
336 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
337 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
338 /// the return value of [`Filter::register_output`].
340 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
341 /// may have been spent there. See [`Filter::register_output`] for details.
343 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
344 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
345 #[derive(Clone, PartialEq, Hash)]
346 pub struct WatchedOutput {
347 /// First block where the transaction output may have been spent.
348 pub block_hash: Option<BlockHash>,
350 /// Outpoint identifying the transaction output.
351 pub outpoint: OutPoint,
353 /// Spending condition of the transaction output.
354 pub script_pubkey: Script,
357 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
358 fn block_connected(&self, block: &Block, height: u32) {
359 (**self).block_connected(block, height);
362 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
363 (**self).block_disconnected(header, height);
367 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
372 fn block_connected(&self, block: &Block, height: u32) {
373 self.0.block_connected(block, height);
374 self.1.block_connected(block, height);
377 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
378 self.0.block_disconnected(header, height);
379 self.1.block_disconnected(header, height);