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::script::Script;
14 use bitcoin::blockdata::transaction::{Transaction, TxOut};
15 use bitcoin::hash_types::{BlockHash, Txid};
17 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
18 use chain::keysinterface::Sign;
19 use chain::transaction::{OutPoint, TransactionData};
23 pub mod chaininterface;
25 pub mod channelmonitor;
27 pub mod keysinterface;
28 pub(crate) mod onchaintx;
29 pub(crate) mod package;
31 /// An error when accessing the chain via [`Access`].
33 pub enum AccessError {
34 /// The requested chain is unknown.
37 /// The requested transaction doesn't exist or hasn't confirmed.
41 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
44 /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`].
45 /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output
48 /// [`short_channel_id`]: https://github.com/lightningnetwork/lightning-rfc/blob/master/07-routing-gossip.md#definition-of-short_channel_id
49 fn get_utxo(&self, genesis_hash: &BlockHash, short_channel_id: u64) -> Result<TxOut, AccessError>;
52 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
55 /// Useful when needing to replay chain data upon startup or as new chain events occur. Clients
56 /// sourcing chain data using a block-oriented API should prefer this interface over [`Confirm`].
57 /// Such clients fetch the entire header chain whereas clients using [`Confirm`] only fetch headers
60 /// Notifies the listener that a block was added at the given height.
61 fn block_connected(&self, block: &Block, height: u32);
63 /// Notifies the listener that a block was removed at the given height.
64 fn block_disconnected(&self, header: &BlockHeader, height: u32);
67 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
68 /// unconfirmed during a chain reorganization.
70 /// Clients sourcing chain data using a transaction-oriented API should prefer this interface over
71 /// [`Listen`]. For instance, an Electrum client may implement [`Filter`] by subscribing to activity
72 /// related to registered transactions and outputs. Upon notification, it would pass along the
73 /// matching transactions using this interface.
77 /// The intended use is as follows:
78 /// - Call [`transactions_confirmed`] to process any on-chain activity of interest.
79 /// - Call [`transaction_unconfirmed`] to process any transaction returned by [`get_relevant_txids`]
80 /// that has been reorganized out of the chain.
81 /// - Call [`best_block_updated`] whenever a new chain tip becomes available.
85 /// Clients must call these methods in chain order. Specifically:
86 /// - Transactions confirmed in a block must be given before transactions confirmed in a later
88 /// - Dependent transactions within the same block must be given in topological order, possibly in
90 /// - Unconfirmed transactions must be given after the original confirmations and before any
93 /// See individual method documentation for further details.
95 /// [`transactions_confirmed`]: Self::transactions_confirmed
96 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
97 /// [`best_block_updated`]: Self::best_block_updated
98 /// [`get_relevant_txids`]: Self::get_relevant_txids
100 /// Processes transactions confirmed in a block with a given header and height.
102 /// Should be called for any transactions registered by [`Filter::register_tx`] or any
103 /// transactions spending an output registered by [`Filter::register_output`]. Such transactions
104 /// appearing in the same block do not need to be included in the same call; instead, multiple
105 /// calls with additional transactions may be made so long as they are made in [chain order].
107 /// May be called before or after [`best_block_updated`] for the corresponding block. However,
108 /// in the event of a chain reorganization, it must not be called with a `header` that is no
109 /// longer in the chain as of the last call to [`best_block_updated`].
111 /// [chain order]: Confirm#Order
112 /// [`best_block_updated`]: Self::best_block_updated
113 fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
115 /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
117 /// Should be called for any transaction returned by [`get_relevant_txids`] if it has been
118 /// reorganized out of the best chain. Once called, the given transaction should not be returned
119 /// by [`get_relevant_txids`] unless it has been reconfirmed via [`transactions_confirmed`].
121 /// [`get_relevant_txids`]: Self::get_relevant_txids
122 /// [`transactions_confirmed`]: Self::transactions_confirmed
123 fn transaction_unconfirmed(&self, txid: &Txid);
125 /// Processes an update to the best header connected at the given height.
127 /// Should be called when a new header is available but may be skipped for intermediary blocks
128 /// if they become available at the same time.
129 fn best_block_updated(&self, header: &BlockHeader, height: u32);
131 /// Returns transactions that should be monitored for reorganization out of the chain.
133 /// Should include any transactions passed to [`transactions_confirmed`] that have insufficient
134 /// confirmations to be safe from a chain reorganization. Should not include any transactions
135 /// passed to [`transaction_unconfirmed`] unless later reconfirmed.
137 /// May be called to determine the subset of transactions that must still be monitored for
138 /// reorganization. Will be idempotent between calls but may change as a result of calls to the
139 /// other interface methods. Thus, this is useful to determine which transactions may need to be
140 /// given to [`transaction_unconfirmed`].
142 /// [`transactions_confirmed`]: Self::transactions_confirmed
143 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
144 fn get_relevant_txids(&self) -> Vec<Txid>;
147 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
148 /// blocks are connected and disconnected.
150 /// Each channel is associated with a [`ChannelMonitor`]. Implementations of this trait are
151 /// responsible for maintaining a set of monitors such that they can be updated accordingly as
152 /// channel state changes and HTLCs are resolved. See method documentation for specific
155 /// Implementations **must** ensure that updates are successfully applied and persisted upon method
156 /// completion. If an update fails with a [`PermanentFailure`], then it must immediately shut down
157 /// without taking any further action such as persisting the current state.
159 /// If an implementation maintains multiple instances of a channel's monitor (e.g., by storing
160 /// backup copies), then it must ensure that updates are applied across all instances. Otherwise, it
161 /// could result in a revoked transaction being broadcast, allowing the counterparty to claim all
162 /// funds in the channel. See [`ChannelMonitorUpdateErr`] for more details about how to handle
163 /// multiple instances.
165 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
166 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
167 /// [`PermanentFailure`]: channelmonitor::ChannelMonitorUpdateErr::PermanentFailure
168 pub trait Watch<ChannelSigner: Sign> {
169 /// Watches a channel identified by `funding_txo` using `monitor`.
171 /// Implementations are responsible for watching the chain for the funding transaction along
172 /// with any spends of outputs returned by [`get_outputs_to_watch`]. In practice, this means
173 /// calling [`block_connected`] and [`block_disconnected`] on the monitor.
175 /// [`get_outputs_to_watch`]: channelmonitor::ChannelMonitor::get_outputs_to_watch
176 /// [`block_connected`]: channelmonitor::ChannelMonitor::block_connected
177 /// [`block_disconnected`]: channelmonitor::ChannelMonitor::block_disconnected
178 fn watch_channel(&self, funding_txo: OutPoint, monitor: ChannelMonitor<ChannelSigner>) -> Result<(), ChannelMonitorUpdateErr>;
180 /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
182 /// Implementations must call [`update_monitor`] with the given update. See
183 /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
185 /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
186 /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
187 fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
189 /// Returns any monitor events since the last call. Subsequent calls must only return new
191 fn release_pending_monitor_events(&self) -> Vec<MonitorEvent>;
194 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
197 /// This is useful in order to have a [`Watch`] implementation convey to a chain source which
198 /// transactions to be notified of. Notification may take the form of pre-filtering blocks or, in
199 /// the case of [BIP 157]/[BIP 158], only fetching a block if the compact filter matches. If
200 /// receiving full blocks from a chain source, any further filtering is unnecessary.
202 /// After an output has been registered, subsequent block retrievals from the chain source must not
203 /// exclude any transactions matching the new criteria nor any in-block descendants of such
206 /// Note that use as part of a [`Watch`] implementation involves reentrancy. Therefore, the `Filter`
207 /// should not block on I/O. Implementations should instead queue the newly monitored data to be
208 /// processed later. Then, in order to block until the data has been processed, any [`Watch`]
209 /// invocation that has called the `Filter` must return [`TemporaryFailure`].
211 /// [`TemporaryFailure`]: channelmonitor::ChannelMonitorUpdateErr::TemporaryFailure
212 /// [BIP 157]: https://github.com/bitcoin/bips/blob/master/bip-0157.mediawiki
213 /// [BIP 158]: https://github.com/bitcoin/bips/blob/master/bip-0158.mediawiki
215 /// Registers interest in a transaction with `txid` and having an output with `script_pubkey` as
216 /// a spending condition.
217 fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
219 /// Registers interest in spends of a transaction output.
221 /// Optionally, when `output.block_hash` is set, should return any transaction spending the
222 /// output that is found in the corresponding block along with its index.
224 /// This return value is useful for Electrum clients in order to supply in-block descendant
225 /// transactions which otherwise were not included. This is not necessary for other clients if
226 /// such descendant transactions were already included (e.g., when a BIP 157 client provides the
228 fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
231 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
233 /// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
234 /// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
235 /// the return value of [`Filter::register_output`].
237 /// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
238 /// may have been spent there. See [`Filter::register_output`] for details.
240 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
241 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
242 pub struct WatchedOutput {
243 /// First block where the transaction output may have been spent.
244 pub block_hash: Option<BlockHash>,
246 /// Outpoint identifying the transaction output.
247 pub outpoint: OutPoint,
249 /// Spending condition of the transaction output.
250 pub script_pubkey: Script,
253 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
254 fn block_connected(&self, block: &Block, height: u32) {
255 (**self).block_connected(block, height);
258 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
259 (**self).block_disconnected(header, height);
263 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
268 fn block_connected(&self, block: &Block, height: u32) {
269 self.0.block_connected(block, height);
270 self.1.block_connected(block, height);
273 fn block_disconnected(&self, header: &BlockHeader, height: u32) {
274 self.0.block_disconnected(header, height);
275 self.1.block_disconnected(header, height);