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