92c9c102597b8546e6ca42f3272d5f0cb9e2289f
[rust-lightning] / lightning / src / chain / chaininterface.rs
1 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
2 //! blockchain.
3 //!
4 //! Includes traits for monitoring and receiving notifications of new blocks and block
5 //! disconnections, transaction broadcasting, and feerate information requests.
6
7 use bitcoin::blockdata::block::{Block, BlockHeader};
8 use bitcoin::blockdata::transaction::Transaction;
9 use bitcoin::blockdata::script::Script;
10 use bitcoin::blockdata::constants::genesis_block;
11 use bitcoin::util::hash::BitcoinHash;
12 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
13 use bitcoin::network::constants::Network;
14
15 use util::logger::Logger;
16
17 use std::sync::{Mutex,Weak,MutexGuard,Arc};
18 use std::sync::atomic::{AtomicUsize, Ordering};
19 use std::collections::HashSet;
20
21 /// Used to give chain error details upstream
22 pub enum ChainError {
23         /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
24         NotSupported,
25         /// Chain isn't the one watched
26         NotWatched,
27         /// Tx doesn't exist or is unconfirmed
28         UnknownTx,
29 }
30
31 /// An interface to request notification of certain scripts as they appear the
32 /// chain.
33 ///
34 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
35 /// called from inside the library in response to ChainListener events, P2P events, or timer
36 /// events).
37 pub trait ChainWatchInterface: Sync + Send {
38         /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
39         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script);
40
41         /// Provides an outpoint which must be watched for, providing any transactions which spend the
42         /// given outpoint.
43         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
44
45         /// Indicates that a listener needs to see all transactions.
46         fn watch_all_txn(&self);
47
48         /// Gets the script and value in satoshis for a given unspent transaction output given a
49         /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
50         /// bytes are the block height, the next 3 the transaction index within the block, and the
51         /// final two the output within the transaction.
52         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
53
54         /// Gets the list of transactions and transaction indices that the ChainWatchInterface is
55         /// watching for.
56         fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>);
57
58         /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
59         /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
60         /// determine whether they need to re-filter a given block.
61         fn reentered(&self) -> usize;
62 }
63
64 /// An interface to send a transaction to the Bitcoin network.
65 pub trait BroadcasterInterface: Sync + Send {
66         /// Sends a transaction out to (hopefully) be mined.
67         fn broadcast_transaction(&self, tx: &Transaction);
68 }
69
70 /// A trait indicating a desire to listen for events from the chain
71 pub trait ChainListener: Sync + Send {
72         /// Notifies a listener that a block was connected.
73         /// Note that if a new transaction/outpoint is watched during a block_connected call, the block
74         /// *must* be re-scanned with the new transaction/outpoints and block_connected should be
75         /// called again with the same header and (at least) the new transactions.
76         ///
77         /// Note that if non-new transaction/outpoints may be registered during a call, a second call
78         /// *must not* happen.
79         ///
80         /// This also means those counting confirmations using block_connected callbacks should watch
81         /// for duplicate headers and not count them towards confirmations!
82         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
83         /// Notifies a listener that a block was disconnected.
84         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
85         /// Height must be the one of the block which was disconnected (not new height of the best chain)
86         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
87 }
88
89 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
90 /// estimation.
91 pub enum ConfirmationTarget {
92         /// We are happy with this transaction confirming slowly when feerate drops some.
93         Background,
94         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
95         Normal,
96         /// We'd like this transaction to confirm in the next few blocks.
97         HighPriority,
98 }
99
100 /// A trait which should be implemented to provide feerate information on a number of time
101 /// horizons.
102 ///
103 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
104 /// called from inside the library in response to ChainListener events, P2P events, or timer
105 /// events).
106 pub trait FeeEstimator: Sync + Send {
107         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
108         ///
109         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
110         /// don't put us below 1 satoshi-per-byte).
111         ///
112         /// This translates to:
113         ///  * satoshis-per-byte * 250
114         ///  * ceil(satoshis-per-kbyte / 4)
115         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
116 }
117
118 /// Utility for tracking registered txn/outpoints and checking for matches
119 pub struct ChainWatchedUtil {
120         watch_all: bool,
121
122         // We are more conservative in matching during testing to ensure everything matches *exactly*,
123         // even though during normal runtime we take more optimized match approaches...
124         #[cfg(test)]
125         watched_txn: HashSet<(Sha256dHash, Script)>,
126         #[cfg(not(test))]
127         watched_txn: HashSet<Script>,
128
129         watched_outpoints: HashSet<(Sha256dHash, u32)>,
130 }
131
132 impl ChainWatchedUtil {
133         /// Constructs an empty (watches nothing) ChainWatchedUtil
134         pub fn new() -> Self {
135                 Self {
136                         watch_all: false,
137                         watched_txn: HashSet::new(),
138                         watched_outpoints: HashSet::new(),
139                 }
140         }
141
142         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
143         /// been watching for it.
144         pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
145                 if self.watch_all { return false; }
146                 #[cfg(test)]
147                 {
148                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
149                 }
150                 #[cfg(not(test))]
151                 {
152                         let _tx_unused = txid; // It's used in cfg(test), though
153                         self.watched_txn.insert(script_pub_key.clone())
154                 }
155         }
156
157         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
158         /// we'd already been watching for it
159         pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
160                 if self.watch_all { return false; }
161                 self.watched_outpoints.insert(outpoint)
162         }
163
164         /// Sets us to match all transactions, returning true if this is a new setting and false if
165         /// we'd already been set to match everything.
166         pub fn watch_all(&mut self) -> bool {
167                 if self.watch_all { return false; }
168                 self.watch_all = true;
169                 true
170         }
171
172         /// Checks if a given transaction matches the current filter.
173         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
174                 if self.watch_all {
175                         return true;
176                 }
177                 for out in tx.output.iter() {
178                         #[cfg(test)]
179                         for &(ref txid, ref script) in self.watched_txn.iter() {
180                                 if *script == out.script_pubkey {
181                                         if tx.txid() == *txid {
182                                                 return true;
183                                         }
184                                 }
185                         }
186                         #[cfg(not(test))]
187                         for script in self.watched_txn.iter() {
188                                 if *script == out.script_pubkey {
189                                         return true;
190                                 }
191                         }
192                 }
193                 for input in tx.input.iter() {
194                         for outpoint in self.watched_outpoints.iter() {
195                                 let &(outpoint_hash, outpoint_index) = outpoint;
196                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
197                                         return true;
198                                 }
199                         }
200                 }
201                 false
202         }
203 }
204
205 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
206 /// data is registered.
207 pub struct BlockNotifier<'a> {
208         listeners: Mutex<Vec<Weak<ChainListener + 'a>>>, //TODO(vmw): try removing Weak
209         chain_monitor: Arc<ChainWatchInterface>,
210 }
211
212 impl<'a> BlockNotifier<'a> {
213         /// Constructs a new BlockNotifier without any listeners.
214         pub fn new(chain_monitor: Arc<ChainWatchInterface>) -> BlockNotifier<'a> {
215                 BlockNotifier {
216                         listeners: Mutex::new(Vec::new()),
217                         chain_monitor,
218                 }
219         }
220
221         /// Register the given listener to receive events. Only a weak pointer is provided and
222         /// the registration should be freed once that pointer expires.
223         // TODO: unregister
224         pub fn register_listener(&self, listener: Weak<ChainListener + 'a>) {
225                 let mut vec = self.listeners.lock().unwrap();
226                 vec.push(listener);
227         }
228
229         /// Notify listeners that a block was connected given a full, unfiltered block.
230         ///
231         /// Handles re-scanning the block and calling block_connected again if listeners register new
232         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
233         pub fn block_connected<'b>(&self, block: &'b Block, height: u32) {
234                 let mut reentered = true;
235                 while reentered {
236                         let (matched, matched_index) = self.chain_monitor.filter_block(block);
237                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
238                 }
239         }
240
241         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
242         /// block which matched the filter (probably using does_match_tx).
243         ///
244         /// Returns true if notified listeners registered additional watch data (implying that the
245         /// block must be re-scanned and this function called again prior to further block_connected
246         /// calls, see ChainListener::block_connected for more info).
247         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
248                 let last_seen = self.chain_monitor.reentered();
249
250                 let listeners = self.listeners.lock().unwrap().clone();
251                 for listener in listeners.iter() {
252                         match listener.upgrade() {
253                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
254                                 None => ()
255                         }
256                 }
257                 return last_seen != self.chain_monitor.reentered();
258         }
259
260
261         /// Notify listeners that a block was disconnected.
262         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
263                 let listeners = self.listeners.lock().unwrap().clone();
264                 for listener in listeners.iter() {
265                         match listener.upgrade() {
266                                 Some(arc) => arc.block_disconnected(&header, disconnected_height),
267                                 None => ()
268                         }
269                 }
270         }
271
272 }
273
274 /// Utility to capture some common parts of ChainWatchInterface implementors.
275 ///
276 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
277 pub struct ChainWatchInterfaceUtil {
278         network: Network,
279         watched: Mutex<ChainWatchedUtil>,
280         reentered: AtomicUsize,
281         logger: Arc<Logger>,
282 }
283
284 /// Register listener
285 impl ChainWatchInterface for ChainWatchInterfaceUtil {
286         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
287                 let mut watched = self.watched.lock().unwrap();
288                 if watched.register_tx(txid, script_pub_key) {
289                         self.reentered.fetch_add(1, Ordering::Relaxed);
290                 }
291         }
292
293         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
294                 let mut watched = self.watched.lock().unwrap();
295                 if watched.register_outpoint(outpoint, out_script) {
296                         self.reentered.fetch_add(1, Ordering::Relaxed);
297                 }
298         }
299
300         fn watch_all_txn(&self) {
301                 let mut watched = self.watched.lock().unwrap();
302                 if watched.watch_all() {
303                         self.reentered.fetch_add(1, Ordering::Relaxed);
304                 }
305         }
306
307         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
308                 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
309                         return Err(ChainError::NotWatched);
310                 }
311                 Err(ChainError::NotSupported)
312         }
313
314         fn filter_block<'a>(&self, block: &'a Block) -> (Vec<&'a Transaction>, Vec<u32>) {
315                 let mut matched = Vec::new();
316                 let mut matched_index = Vec::new();
317                 {
318                         let watched = self.watched.lock().unwrap();
319                         for (index, transaction) in block.txdata.iter().enumerate() {
320                                 if self.does_match_tx_unguarded(transaction, &watched) {
321                                         matched.push(transaction);
322                                         matched_index.push(index as u32);
323                                 }
324                         }
325                 }
326                 (matched, matched_index)
327         }
328
329         fn reentered(&self) -> usize {
330                 self.reentered.load(Ordering::Relaxed)
331         }
332 }
333
334 impl ChainWatchInterfaceUtil {
335         /// Creates a new ChainWatchInterfaceUtil for the given network
336         pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
337                 ChainWatchInterfaceUtil {
338                         network: network,
339                         watched: Mutex::new(ChainWatchedUtil::new()),
340                         reentered: AtomicUsize::new(1),
341                         logger: logger,
342                 }
343         }
344
345
346         /// Checks if a given transaction matches the current filter.
347         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
348                 let watched = self.watched.lock().unwrap();
349                 self.does_match_tx_unguarded (tx, &watched)
350         }
351
352         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
353                 watched.does_match_tx(tx)
354         }
355 }