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