8f27e40baeaf1e3b5d43dade8a05da0bb08dfdcb
[rust-lightning] / lightning / src / 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
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};
16
17 use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
18 use chain::keysinterface::Sign;
19 use chain::transaction::{OutPoint, TransactionData};
20
21 use prelude::*;
22
23 pub mod chaininterface;
24 pub mod chainmonitor;
25 pub mod channelmonitor;
26 pub mod transaction;
27 pub mod keysinterface;
28 pub(crate) mod onchaintx;
29 pub(crate) mod package;
30
31 /// An error when accessing the chain via [`Access`].
32 #[derive(Clone)]
33 pub enum AccessError {
34         /// The requested chain is unknown.
35         UnknownChain,
36
37         /// The requested transaction doesn't exist or hasn't confirmed.
38         UnknownTx,
39 }
40
41 /// The `Access` trait defines behavior for accessing chain data and state, such as blocks and
42 /// UTXOs.
43 pub trait Access {
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
46         /// is unknown.
47         ///
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>;
50 }
51
52 /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the
53 /// chain.
54 ///
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
58 /// when needed.
59 pub trait Listen {
60         /// Notifies the listener that a block was added at the given height.
61         fn block_connected(&self, block: &Block, height: u32);
62
63         /// Notifies the listener that a block was removed at the given height.
64         fn block_disconnected(&self, header: &BlockHeader, height: u32);
65 }
66
67 /// The `Confirm` trait is used to notify when transactions have been confirmed on chain or
68 /// unconfirmed during a chain reorganization.
69 ///
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.
74 ///
75 /// # Use
76 ///
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.
82 ///
83 /// # Order
84 ///
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
87 ///   block.
88 /// - Dependent transactions within the same block must be given in topological order, possibly in
89 ///   separate calls.
90 /// - Unconfirmed transactions must be given after the original confirmations and before any
91 ///   reconfirmation.
92 ///
93 /// See individual method documentation for further details.
94 ///
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
99 pub trait Confirm {
100         /// Processes transactions confirmed in a block with a given header and height.
101         ///
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].
106         ///
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`].
110         ///
111         /// [chain order]: Confirm#Order
112         /// [`best_block_updated`]: Self::best_block_updated
113         fn transactions_confirmed(&self, header: &BlockHeader, txdata: &TransactionData, height: u32);
114
115         /// Processes a transaction that is no longer confirmed as result of a chain reorganization.
116         ///
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`].
120         ///
121         /// [`get_relevant_txids`]: Self::get_relevant_txids
122         /// [`transactions_confirmed`]: Self::transactions_confirmed
123         fn transaction_unconfirmed(&self, txid: &Txid);
124
125         /// Processes an update to the best header connected at the given height.
126         ///
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);
130
131         /// Returns transactions that should be monitored for reorganization out of the chain.
132         ///
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.
136         ///
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`].
141         ///
142         /// [`transactions_confirmed`]: Self::transactions_confirmed
143         /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
144         fn get_relevant_txids(&self) -> Vec<Txid>;
145 }
146
147 /// The `Watch` trait defines behavior for watching on-chain activity pertaining to channels as
148 /// blocks are connected and disconnected.
149 ///
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
153 /// requirements.
154 ///
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.
158 ///
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.
164 ///
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`.
170         ///
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.
174         ///
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>;
179
180         /// Updates a channel identified by `funding_txo` by applying `update` to its monitor.
181         ///
182         /// Implementations must call [`update_monitor`] with the given update. See
183         /// [`ChannelMonitorUpdateErr`] for invariants around returning an error.
184         ///
185         /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor
186         /// [`ChannelMonitorUpdateErr`]: channelmonitor::ChannelMonitorUpdateErr
187         fn update_channel(&self, funding_txo: OutPoint, update: ChannelMonitorUpdate) -> Result<(), ChannelMonitorUpdateErr>;
188
189         /// Returns any monitor events since the last call. Subsequent calls must only return new
190         /// events.
191         fn release_pending_monitor_events(&self) -> Vec<MonitorEvent>;
192 }
193
194 /// The `Filter` trait defines behavior for indicating chain activity of interest pertaining to
195 /// channels.
196 ///
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.
201 ///
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
204 /// transactions.
205 ///
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`].
210 ///
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
214 pub trait Filter {
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);
218
219         /// Registers interest in spends of a transaction output.
220         ///
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.
223         ///
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
227         /// full block).
228         fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
229 }
230
231 /// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
232 ///
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`].
236 ///
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.
239 ///
240 /// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
241 /// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
242 #[derive(Clone, PartialEq, Hash)]
243 pub struct WatchedOutput {
244         /// First block where the transaction output may have been spent.
245         pub block_hash: Option<BlockHash>,
246
247         /// Outpoint identifying the transaction output.
248         pub outpoint: OutPoint,
249
250         /// Spending condition of the transaction output.
251         pub script_pubkey: Script,
252 }
253
254 impl<T: Listen> Listen for core::ops::Deref<Target = T> {
255         fn block_connected(&self, block: &Block, height: u32) {
256                 (**self).block_connected(block, height);
257         }
258
259         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
260                 (**self).block_disconnected(header, height);
261         }
262 }
263
264 impl<T: core::ops::Deref, U: core::ops::Deref> Listen for (T, U)
265 where
266         T::Target: Listen,
267         U::Target: Listen,
268 {
269         fn block_connected(&self, block: &Block, height: u32) {
270                 self.0.block_connected(block, height);
271                 self.1.block_connected(block, height);
272         }
273
274         fn block_disconnected(&self, header: &BlockHeader, height: u32) {
275                 self.0.block_disconnected(header, height);
276                 self.1.block_disconnected(header, height);
277         }
278 }