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