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