Do not test any block-contents-rescan cases
[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 ///
230 /// (C-not exported) as we let clients handle any reference counting they need to do
231 pub type BlockNotifierArc<C> = Arc<BlockNotifier<'static, Arc<ChainListener>, C>>;
232
233 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
234 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
235 /// lifetimes are more efficient but less flexible, and should be used by default unless static
236 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
237 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
238 /// appropriate type. Defining these type aliases for common usages prevents issues such as
239 /// overly long function definitions.
240 pub type BlockNotifierRef<'a, C> = BlockNotifier<'a, &'a ChainListener, C>;
241
242 /// Utility for notifying listeners about new blocks, and handling block rescans if new watch
243 /// data is registered.
244 ///
245 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
246 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
247 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
248 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
249 pub struct BlockNotifier<'a, CL: Deref + 'a, C: Deref>
250                 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
251         listeners: Mutex<Vec<CL>>,
252         chain_monitor: C,
253         phantom: PhantomData<&'a ()>,
254 }
255
256 impl<'a, CL: Deref + 'a, C: Deref> BlockNotifier<'a, CL, C>
257                 where CL::Target: ChainListener + 'a, C::Target: ChainWatchInterface {
258         /// Constructs a new BlockNotifier without any listeners.
259         pub fn new(chain_monitor: C) -> BlockNotifier<'a, CL, C> {
260                 BlockNotifier {
261                         listeners: Mutex::new(Vec::new()),
262                         chain_monitor,
263                         phantom: PhantomData,
264                 }
265         }
266
267         /// Register the given listener to receive events.
268         pub fn register_listener(&self, listener: CL) {
269                 let mut vec = self.listeners.lock().unwrap();
270                 vec.push(listener);
271         }
272         /// Unregister the given listener to no longer
273         /// receive events.
274         ///
275         /// If the same listener is registered multiple times, unregistering
276         /// will remove ALL occurrences of that listener. Comparison is done using
277         /// the pointer returned by the Deref trait implementation.
278         ///
279         /// (C-not exported) because the equality check would always fail
280         pub fn unregister_listener(&self, listener: CL) {
281                 let mut vec = self.listeners.lock().unwrap();
282                 // item is a ref to an abstract thing that dereferences to a ChainListener,
283                 // so dereference it twice to get the ChainListener itself
284                 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
285         }
286
287         /// Notify listeners that a block was connected given a full, unfiltered block.
288         ///
289         /// Handles re-scanning the block and calling block_connected again if listeners register new
290         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
291         pub fn block_connected(&self, block: &Block, height: u32) {
292                 let mut reentered = true;
293                 while reentered {
294                         let matched_indexes = self.chain_monitor.filter_block(block);
295                         let mut matched_txn = Vec::new();
296                         for index in matched_indexes.iter() {
297                                 matched_txn.push(&block.txdata[*index]);
298                         }
299                         reentered = self.block_connected_checked(&block.header, height, matched_txn.as_slice(), matched_indexes.as_slice());
300                 }
301         }
302
303         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
304         /// block which matched the filter (probably using does_match_tx).
305         ///
306         /// Returns true if notified listeners registered additional watch data (implying that the
307         /// block must be re-scanned and this function called again prior to further block_connected
308         /// calls, see ChainListener::block_connected for more info).
309         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[usize]) -> bool {
310                 let last_seen = self.chain_monitor.reentered();
311
312                 let listeners = self.listeners.lock().unwrap();
313                 for listener in listeners.iter() {
314                         listener.block_connected(header, height, txn_matched, indexes_of_txn_matched);
315                 }
316                 return last_seen != self.chain_monitor.reentered();
317         }
318
319         /// Notify listeners that a block was disconnected.
320         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
321                 let listeners = self.listeners.lock().unwrap();
322                 for listener in listeners.iter() {
323                         listener.block_disconnected(&header, disconnected_height);
324                 }
325         }
326 }
327
328 /// Utility to capture some common parts of ChainWatchInterface implementors.
329 ///
330 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
331 pub struct ChainWatchInterfaceUtil {
332         network: Network,
333         watched: Mutex<ChainWatchedUtil>,
334         reentered: AtomicUsize,
335 }
336
337 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
338 // only comparing a subset of fields (essentially just checking that the set of things we're
339 // watching is the same).
340 #[cfg(test)]
341 impl PartialEq for ChainWatchInterfaceUtil {
342         fn eq(&self, o: &Self) -> bool {
343                 self.network == o.network &&
344                 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
345         }
346 }
347
348 /// Register listener
349 impl ChainWatchInterface for ChainWatchInterfaceUtil {
350         fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
351                 let mut watched = self.watched.lock().unwrap();
352                 if watched.register_tx(txid, script_pub_key) {
353                         self.reentered.fetch_add(1, Ordering::Relaxed);
354                 }
355         }
356
357         fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
358                 let mut watched = self.watched.lock().unwrap();
359                 if watched.register_outpoint(outpoint, out_script) {
360                         self.reentered.fetch_add(1, Ordering::Relaxed);
361                 }
362         }
363
364         fn watch_all_txn(&self) {
365                 let mut watched = self.watched.lock().unwrap();
366                 if watched.watch_all() {
367                         self.reentered.fetch_add(1, Ordering::Relaxed);
368                 }
369         }
370
371         fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
372                 if genesis_hash != genesis_block(self.network).header.block_hash() {
373                         return Err(ChainError::NotWatched);
374                 }
375                 Err(ChainError::NotSupported)
376         }
377
378         fn filter_block(&self, block: &Block) -> Vec<usize> {
379                 let mut matched_index = Vec::new();
380                 let mut matched_txids = HashSet::new();
381                 {
382                         let watched = self.watched.lock().unwrap();
383                         for (index, transaction) in block.txdata.iter().enumerate() {
384                                 // A tx matches the filter if it either matches the filter directly (via
385                                 // does_match_tx_unguarded) or if it is a descendant of another matched
386                                 // transaction within the same block, which we check for in the loop.
387                                 let mut matched = self.does_match_tx_unguarded(transaction, &watched);
388                                 for input in transaction.input.iter() {
389                                         if matched || matched_txids.contains(&input.previous_output.txid) {
390                                                 matched = true;
391                                                 break;
392                                         }
393                                 }
394                                 if matched {
395                                         matched_txids.insert(transaction.txid());
396                                         matched_index.push(index);
397                                 }
398                         }
399                 }
400                 matched_index
401         }
402
403         fn reentered(&self) -> usize {
404                 self.reentered.load(Ordering::Relaxed)
405         }
406 }
407
408 impl ChainWatchInterfaceUtil {
409         /// Creates a new ChainWatchInterfaceUtil for the given network
410         pub fn new(network: Network) -> ChainWatchInterfaceUtil {
411                 ChainWatchInterfaceUtil {
412                         network,
413                         watched: Mutex::new(ChainWatchedUtil::new()),
414                         reentered: AtomicUsize::new(1),
415                 }
416         }
417
418         /// Checks if a given transaction matches the current filter.
419         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
420                 let watched = self.watched.lock().unwrap();
421                 self.does_match_tx_unguarded (tx, &watched)
422         }
423
424         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
425                 watched.does_match_tx(tx)
426         }
427 }
428
429 #[cfg(test)]
430 mod tests {
431         use ln::functional_test_utils::{create_chanmon_cfgs, create_node_cfgs};
432         use super::{BlockNotifier, ChainListener};
433         use std::ptr;
434
435         #[test]
436         fn register_listener_test() {
437                 let chanmon_cfgs = create_chanmon_cfgs(1);
438                 let node_cfgs = create_node_cfgs(1, &chanmon_cfgs);
439                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
440                 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
441                 let listener = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
442                 block_notifier.register_listener(listener);
443                 let vec = block_notifier.listeners.lock().unwrap();
444                 assert_eq!(vec.len(), 1);
445                 let item = vec.first().clone().unwrap();
446                 assert!(ptr::eq(&(**item), &(*listener)));
447         }
448
449         #[test]
450         fn unregister_single_listener_test() {
451                 let chanmon_cfgs = create_chanmon_cfgs(2);
452                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
453                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
454                 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
455                 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
456                 block_notifier.register_listener(listener1);
457                 block_notifier.register_listener(listener2);
458                 let vec = block_notifier.listeners.lock().unwrap();
459                 assert_eq!(vec.len(), 2);
460                 drop(vec);
461                 block_notifier.unregister_listener(listener1);
462                 let vec = block_notifier.listeners.lock().unwrap();
463                 assert_eq!(vec.len(), 1);
464                 let item = vec.first().clone().unwrap();
465                 assert!(ptr::eq(&(**item), &(*listener2)));
466         }
467
468         #[test]
469         fn unregister_single_listener_ref_test() {
470                 let chanmon_cfgs = create_chanmon_cfgs(2);
471                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
472                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
473                 block_notifier.register_listener(&node_cfgs[0].chan_monitor.simple_monitor as &ChainListener);
474                 block_notifier.register_listener(&node_cfgs[1].chan_monitor.simple_monitor as &ChainListener);
475                 let vec = block_notifier.listeners.lock().unwrap();
476                 assert_eq!(vec.len(), 2);
477                 drop(vec);
478                 block_notifier.unregister_listener(&node_cfgs[0].chan_monitor.simple_monitor);
479                 let vec = block_notifier.listeners.lock().unwrap();
480                 assert_eq!(vec.len(), 1);
481                 let item = vec.first().clone().unwrap();
482                 assert!(ptr::eq(&(**item), &(*&node_cfgs[1].chan_monitor.simple_monitor)));
483         }
484
485         #[test]
486         fn unregister_multiple_of_the_same_listeners_test() {
487                 let chanmon_cfgs = create_chanmon_cfgs(2);
488                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
489                 let block_notifier = BlockNotifier::new(node_cfgs[0].chain_monitor);
490                 let listener1 = &node_cfgs[0].chan_monitor.simple_monitor as &ChainListener;
491                 let listener2 = &node_cfgs[1].chan_monitor.simple_monitor as &ChainListener;
492                 block_notifier.register_listener(listener1);
493                 block_notifier.register_listener(listener1);
494                 block_notifier.register_listener(listener2);
495                 let vec = block_notifier.listeners.lock().unwrap();
496                 assert_eq!(vec.len(), 3);
497                 drop(vec);
498                 block_notifier.unregister_listener(listener1);
499                 let vec = block_notifier.listeners.lock().unwrap();
500                 assert_eq!(vec.len(), 1);
501                 let item = vec.first().clone().unwrap();
502                 assert!(ptr::eq(&(**item), &(*listener2)));
503         }
504 }