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