Update to latest upstream rust-bitcoin
[rust-lightning] / lightning / src / chain / chaininterface.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 //! Traits and utility impls which allow other parts of rust-lightning to interact with the
11 //! blockchain.
12 //!
13 //! Includes traits for monitoring and receiving notifications of new blocks and block
14 //! disconnections, transaction broadcasting, and feerate information requests.
15
16 use bitcoin::blockdata::block::{Block, BlockHeader};
17 use bitcoin::blockdata::transaction::Transaction;
18 use bitcoin::blockdata::script::Script;
19 use bitcoin::blockdata::constants::genesis_block;
20 use bitcoin::network::constants::Network;
21 use bitcoin::hash_types::{Txid, BlockHash};
22
23 use std::sync::{Mutex, MutexGuard, Arc};
24 use std::sync::atomic::{AtomicUsize, Ordering};
25 use std::collections::HashSet;
26 use std::ops::Deref;
27 use std::marker::PhantomData;
28 use std::ptr;
29
30 /// Used to give chain error details upstream
31 #[derive(Clone)]
32 pub enum ChainError {
33         /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
34         NotSupported,
35         /// Chain isn't the one watched
36         NotWatched,
37         /// Tx doesn't exist or is unconfirmed
38         UnknownTx,
39 }
40
41 /// An interface to request notification of certain scripts as they appear the
42 /// chain.
43 ///
44 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
45 /// called from inside the library in response to ChainListener events, P2P events, or timer
46 /// events).
47 pub trait ChainWatchInterface: Sync + Send {
48         /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
49         fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script);
50
51         /// Provides an outpoint which must be watched for, providing any transactions which spend the
52         /// given outpoint.
53         fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script);
54
55         /// Indicates that a listener needs to see all transactions.
56         fn watch_all_txn(&self);
57
58         /// Gets the script and value in satoshis for a given unspent transaction output given a
59         /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
60         /// bytes are the block height, the next 3 the transaction index within the block, and the
61         /// final two the output within the transaction.
62         fn get_chain_utxo(&self, genesis_hash: BlockHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
63
64         /// Gets the list of transaction indices within a given block that the ChainWatchInterface is
65         /// watching for.
66         fn filter_block(&self, block: &Block) -> Vec<usize>;
67
68         /// Returns a usize that changes when the ChainWatchInterface's watched data is modified.
69         /// Users of `filter_block` should pre-save a copy of `reentered`'s return value and use it to
70         /// determine whether they need to re-filter a given block.
71         fn reentered(&self) -> usize;
72 }
73
74 /// An interface to send a transaction to the Bitcoin network.
75 pub trait BroadcasterInterface: Sync + Send {
76         /// Sends a transaction out to (hopefully) be mined.
77         fn broadcast_transaction(&self, tx: &Transaction);
78 }
79
80 /// A trait indicating a desire to listen for events from the chain
81 pub trait ChainListener: Sync + Send {
82         /// Notifies a listener that a block was connected.
83         ///
84         /// The txn_matched array should be set to references to transactions which matched the
85         /// relevant installed watch outpoints/txn, or the full set of transactions in the block.
86         ///
87         /// Note that if txn_matched includes only matched transactions, and a new
88         /// transaction/outpoint is watched during a block_connected call, the block *must* be
89         /// re-scanned with the new transaction/outpoints and block_connected should be called
90         /// again with the same header and (at least) the new transactions.
91         ///
92         /// Note that if non-new transaction/outpoints are be registered during a call, a second call
93         /// *must not* happen.
94         ///
95         /// This also means those counting confirmations using block_connected callbacks should watch
96         /// for duplicate headers and not count them towards confirmations!
97         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]);
98         /// Notifies a listener that a block was disconnected.
99         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
100         /// Height must be the one of the block which was disconnected (not new height of the best chain)
101         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
102 }
103
104 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
105 /// estimation.
106 pub enum ConfirmationTarget {
107         /// We are happy with this transaction confirming slowly when feerate drops some.
108         Background,
109         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
110         Normal,
111         /// We'd like this transaction to confirm in the next few blocks.
112         HighPriority,
113 }
114
115 /// A trait which should be implemented to provide feerate information on a number of time
116 /// horizons.
117 ///
118 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
119 /// called from inside the library in response to ChainListener events, P2P events, or timer
120 /// events).
121 pub trait FeeEstimator: Sync + Send {
122         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
123         ///
124         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
125         /// don't put us below 1 satoshi-per-byte).
126         ///
127         /// This translates to:
128         ///  * satoshis-per-byte * 250
129         ///  * ceil(satoshis-per-kbyte / 4)
130         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
131 }
132
133 /// Minimum relay fee as required by bitcoin network mempool policy.
134 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
135
136 /// Utility for tracking registered txn/outpoints and checking for matches
137 #[cfg_attr(test, derive(PartialEq))]
138 pub struct ChainWatchedUtil {
139         watch_all: bool,
140
141         // We are more conservative in matching during testing to ensure everything matches *exactly*,
142         // even though during normal runtime we take more optimized match approaches...
143         #[cfg(test)]
144         watched_txn: HashSet<(Txid, Script)>,
145         #[cfg(not(test))]
146         watched_txn: HashSet<Script>,
147
148         watched_outpoints: HashSet<(Txid, u32)>,
149 }
150
151 impl ChainWatchedUtil {
152         /// Constructs an empty (watches nothing) ChainWatchedUtil
153         pub fn new() -> Self {
154                 Self {
155                         watch_all: false,
156                         watched_txn: HashSet::new(),
157                         watched_outpoints: HashSet::new(),
158                 }
159         }
160
161         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
162         /// been watching for it.
163         pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
164                 if self.watch_all { return false; }
165                 #[cfg(test)]
166                 {
167                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
168                 }
169                 #[cfg(not(test))]
170                 {
171                         let _tx_unused = txid; // It's used in cfg(test), though
172                         self.watched_txn.insert(script_pub_key.clone())
173                 }
174         }
175
176         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
177         /// we'd already been watching for it
178         pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
179                 if self.watch_all { return false; }
180                 self.watched_outpoints.insert(outpoint)
181         }
182
183         /// Sets us to match all transactions, returning true if this is a new setting and false if
184         /// we'd already been set to match everything.
185         pub fn watch_all(&mut self) -> bool {
186                 if self.watch_all { return false; }
187                 self.watch_all = true;
188                 true
189         }
190
191         /// Checks if a given transaction matches the current filter.
192         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
193                 if self.watch_all {
194                         return true;
195                 }
196                 for out in tx.output.iter() {
197                         #[cfg(test)]
198                         for &(ref txid, ref script) in self.watched_txn.iter() {
199                                 if *script == out.script_pubkey {
200                                         if tx.txid() == *txid {
201                                                 return true;
202                                         }
203                                 }
204                         }
205                         #[cfg(not(test))]
206                         for script in self.watched_txn.iter() {
207                                 if *script == out.script_pubkey {
208                                         return true;
209                                 }
210                         }
211                 }
212                 for input in tx.input.iter() {
213                         for outpoint in self.watched_outpoints.iter() {
214                                 let &(outpoint_hash, outpoint_index) = outpoint;
215                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
216                                         return true;
217                                 }
218                         }
219                 }
220                 false
221         }
222 }
223
224 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
225 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
226 /// parameters with static lifetimes). Other times you can afford a reference, which is more
227 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
228 /// aliases prevents issues such as overly long function definitions.
229 pub type BlockNotifierArc<C> = Arc<BlockNotifier<'static, Arc<ChainListener>, C>>;
230
231 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
232 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
233 /// lifetimes are more efficient but less flexible, and should be used by default unless static
234 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
235 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
236 /// appropriate type. Defining these type aliases for common usages prevents issues such as
237 /// overly long function definitions.
238 pub type BlockNotifierRef<'a, C> = BlockNotifier<'a, &'a ChainListener, C>;
239
240 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
241 /// data is registered.
242 ///
243 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
244 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
245 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
246 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
247 pub struct BlockNotifier<'a, CL: Deref + 'a, C: Deref>
248                 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
249         listeners: Mutex<Vec<CL>>,
250         chain_monitor: C,
251         phantom: PhantomData<&'a ()>,
252 }
253
254 impl<'a, CL: Deref + 'a, C: Deref> BlockNotifier<'a, CL, C>
255                 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
256         /// Constructs a new BlockNotifier without any listeners.
257         pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
258                 BlockNotifier {
259                         listeners: Mutex::new(Vec::new()),
260                         chain_monitor,
261                         phantom: PhantomData,
262                 }
263         }
264
265         /// Register the given listener to receive events.
266         pub fn register_listener(&self, listener: CL) {
267                 let mut vec = self.listeners.lock().unwrap();
268                 vec.push(listener);
269         }
270         /// Unregister the given listener to no longer
271         /// receive events.
272         ///
273         /// If the same listener is registered multiple times, unregistering
274         /// will remove ALL occurrences of that listener. Comparison is done using
275         /// the pointer returned by the Deref trait implementation.
276         pub fn unregister_listener(&self, listener: CL) {
277                 let mut vec = self.listeners.lock().unwrap();
278                 // item is a ref to an abstract thing that dereferences to a ChainListener,
279                 // so dereference it twice to get the ChainListener itself
280                 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
281         }
282
283         /// Notify listeners that a block was connected given a full, unfiltered block.
284         ///
285         /// Handles re-scanning the block and calling block_connected again if listeners register new
286         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
287         pub fn block_connected(&self, block: &Block, height: u32) {
288                 let mut reentered = true;
289                 while reentered {
290                         let matched_indexes = self.chain_monitor.filter_block(block);
291                         let mut matched_txn = Vec::new();
292                         for index in matched_indexes.iter() {
293                                 matched_txn.push(&block.txdata[*index]);
294                         }
295                         reentered = self.block_connected_checked(&block.header, height, matched_txn.as_slice(), matched_indexes.as_slice());
296                 }
297         }
298
299         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
300         /// block which matched the filter (probably using does_match_tx).
301         ///
302         /// Returns true if notified listeners registered additional watch data (implying that the
303         /// block must be re-scanned and this function called again prior to further block_connected
304         /// calls, see ChainListener::block_connected for more info).
305         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> bool {
306                 let last_seen = self.chain_monitor.reentered();
307
308                 let listeners = self.listeners.lock().unwrap();
309                 for listener in listeners.iter() {
310                         listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
311                 }
312                 return last_seen != self.chain_monitor.reentered();
313         }
314
315         /// Notify listeners that a block was disconnected.
316         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
317                 let listeners = self.listeners.lock().unwrap();
318                 for listener in listeners.iter() {
319                         listener.block_disconnected(&header, disconnected_height);
320                 }
321         }
322 }
323
324 /// Utility to capture some common parts of ChainWatchInterface implementors.
325 ///
326 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
327 pub struct ChainWatchInterfaceUtil {
328         network: Network,
329         watched: Mutex<ChainWatchedUtil>,
330         reentered: AtomicUsize,
331 }
332
333 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
334 // only comparing a subset of fields (essentially just checking that the set of things we're
335 // watching is the same).
336 #[cfg(test)]
337 impl PartialEq for ChainWatchInterfaceUtil {
338         fn eq(&self, o: &Self) -> bool {
339                 self.network == o.network &&
340                 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
341         }
342 }
343
344 /// Register listener
345 impl ChainWatchInterface for ChainWatchInterfaceUtil {
346         fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
347                 let mut watched = self.watched.lock().unwrap();
348                 if watched.register_tx(txid, script_pub_key) {
349                         self.reentered.fetch_add(1, Ordering::Relaxed);
350                 }
351         }
352
353         fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
354                 let mut watched = self.watched.lock().unwrap();
355                 if watched.register_outpoint(outpoint, out_script) {
356                         self.reentered.fetch_add(1, Ordering::Relaxed);
357                 }
358         }
359
360         fn watch_all_txn(&self) {
361                 let mut watched = self.watched.lock().unwrap();
362                 if watched.watch_all() {
363                         self.reentered.fetch_add(1, Ordering::Relaxed);
364                 }
365         }
366
367         fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
368                 if genesis_hash != genesis_block(self.network).header.block_hash() {
369                         return Err(ChainError::NotWatched);
370                 }
371                 Err(ChainError::NotSupported)
372         }
373
374         fn filter_block(&self, block: &Block) -> Vec<usize> {
375                 let mut matched_index = Vec::new();
376                 {
377                         let watched = self.watched.lock().unwrap();
378                         for (index, transaction) in block.txdata.iter().enumerate() {
379                                 if self.does_match_tx_unguarded(transaction, &watched) {
380                                         matched_index.push(index);
381                                 }
382                         }
383                 }
384                 matched_index
385         }
386
387         fn reentered(&self) -> usize {
388                 self.reentered.load(Ordering::Relaxed)
389         }
390 }
391
392 impl ChainWatchInterfaceUtil {
393         /// Creates a new ChainWatchInterfaceUtil for the given network
394         pub fn new(network: Network) -> ChainWatchInterfaceUtil {
395                 ChainWatchInterfaceUtil {
396                         network,
397                         watched: Mutex::new(ChainWatchedUtil::new()),
398                         reentered: AtomicUsize::new(1),
399                 }
400         }
401
402         /// Checks if a given transaction matches the current filter.
403         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
404                 let watched = self.watched.lock().unwrap();
405                 self.does_match_tx_unguarded (tx, &watched)
406         }
407
408         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
409                 watched.does_match_tx(tx)
410         }
411 }
412
413 #[cfg(test)]
414 mod tests {
415         use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
416         use super::{BlockNotifier, ChainListener};
417         use std::ptr;
418
419         #[test]
420         fn register_listener_test() {
421                 let chanmon_cfgs = create_chanmon_cfgs(1);
422                 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
423                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
424                 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
425                 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
426                 block_notifier.register_listener(listener);
427                 let vec = block_notifier.listeners.lock().unwrap();
428                 assert_eq!(vec.len(), 1);
429                 let item = vec.first().clone().unwrap();
430                 assert!(ptr::eq(&(**item), &(*listener)));
431         }
432
433         #[test]
434         fn unregister_single_listener_test() {
435                 let chanmon_cfgs = create_chanmon_cfgs(2);
436                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
438                 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
439                 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
440                 block_notifier.register_listener(listener1);
441                 block_notifier.register_listener(listener2);
442                 let vec = block_notifier.listeners.lock().unwrap();
443                 assert_eq!(vec.len(), 2);
444                 drop(vec);
445                 block_notifier.unregister_listener(listener1);
446                 let vec = block_notifier.listeners.lock().unwrap();
447                 assert_eq!(vec.len(), 1);
448                 let item = vec.first().clone().unwrap();
449                 assert!(ptr::eq(&(**item), &(*listener2)));
450         }
451
452         #[test]
453         fn unregister_single_listener_ref_test() {
454                 let chanmon_cfgs = create_chanmon_cfgs(2);
455                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
456                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
457                 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
458                 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
459                 let vec = block_notifier.listeners.lock().unwrap();
460                 assert_eq!(vec.len(), 2);
461                 drop(vec);
462                 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
463                 let vec = block_notifier.listeners.lock().unwrap();
464                 assert_eq!(vec.len(), 1);
465                 let item = vec.first().clone().unwrap();
466                 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
467         }
468
469         #[test]
470         fn unregister_multiple_of_the_same_listeners_test() {
471                 let chanmon_cfgs = create_chanmon_cfgs(2);
472                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
473                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
474                 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
475                 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
476                 block_notifier.register_listener(listener1);
477                 block_notifier.register_listener(listener1);
478                 block_notifier.register_listener(listener2);
479                 let vec = block_notifier.listeners.lock().unwrap();
480                 assert_eq!(vec.len(), 3);
481                 drop(vec);
482                 block_notifier.unregister_listener(listener1);
483                 let vec = block_notifier.listeners.lock().unwrap();
484                 assert_eq!(vec.len(), 1);
485                 let item = vec.first().clone().unwrap();
486                 assert!(ptr::eq(&(**item), &(*listener2)));
487         }
488 }