21a2d578d1497496ffaf7092606de44de88078ed
[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, header: &BlockHeader, txdata: &[(usize, &Transaction)]) -> 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. Transactions may be filtered and are given
83         /// paired with their position within the block.
84         fn block_connected(&self, header: &BlockHeader, txdata: &[(usize, &Transaction)], height: u32);
85
86         /// Notifies a listener that a block was disconnected.
87         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
88         /// Height must be the one of the block which was disconnected (not new height of the best chain)
89         fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32);
90 }
91
92 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
93 /// estimation.
94 pub enum ConfirmationTarget {
95         /// We are happy with this transaction confirming slowly when feerate drops some.
96         Background,
97         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
98         Normal,
99         /// We'd like this transaction to confirm in the next few blocks.
100         HighPriority,
101 }
102
103 /// A trait which should be implemented to provide feerate information on a number of time
104 /// horizons.
105 ///
106 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
107 /// called from inside the library in response to ChainListener events, P2P events, or timer
108 /// events).
109 pub trait FeeEstimator: Sync + Send {
110         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
111         ///
112         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
113         /// don't put us below 1 satoshi-per-byte).
114         ///
115         /// This translates to:
116         ///  * satoshis-per-byte * 250
117         ///  * ceil(satoshis-per-kbyte / 4)
118         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u32;
119 }
120
121 /// Minimum relay fee as required by bitcoin network mempool policy.
122 pub const MIN_RELAY_FEE_SAT_PER_1000_WEIGHT: u64 = 4000;
123
124 /// Utility for tracking registered txn/outpoints and checking for matches
125 #[cfg_attr(test, derive(PartialEq))]
126 pub struct ChainWatchedUtil {
127         watch_all: bool,
128
129         // We are more conservative in matching during testing to ensure everything matches *exactly*,
130         // even though during normal runtime we take more optimized match approaches...
131         #[cfg(test)]
132         watched_txn: HashSet<(Txid, Script)>,
133         #[cfg(not(test))]
134         watched_txn: HashSet<Script>,
135
136         watched_outpoints: HashSet<(Txid, u32)>,
137 }
138
139 impl ChainWatchedUtil {
140         /// Constructs an empty (watches nothing) ChainWatchedUtil
141         pub fn new() -> Self {
142                 Self {
143                         watch_all: false,
144                         watched_txn: HashSet::new(),
145                         watched_outpoints: HashSet::new(),
146                 }
147         }
148
149         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
150         /// been watching for it.
151         pub fn register_tx(&mut self, txid: &Txid, script_pub_key: &Script) -> bool {
152                 if self.watch_all { return false; }
153                 #[cfg(test)]
154                 {
155                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
156                 }
157                 #[cfg(not(test))]
158                 {
159                         let _tx_unused = txid; // It's used in cfg(test), though
160                         self.watched_txn.insert(script_pub_key.clone())
161                 }
162         }
163
164         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
165         /// we'd already been watching for it
166         pub fn register_outpoint(&mut self, outpoint: (Txid, u32), _script_pub_key: &Script) -> bool {
167                 if self.watch_all { return false; }
168                 self.watched_outpoints.insert(outpoint)
169         }
170
171         /// Sets us to match all transactions, returning true if this is a new setting and false if
172         /// we'd already been set to match everything.
173         pub fn watch_all(&mut self) -> bool {
174                 if self.watch_all { return false; }
175                 self.watch_all = true;
176                 true
177         }
178
179         /// Checks if a given transaction matches the current filter.
180         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
181                 if self.watch_all {
182                         return true;
183                 }
184                 for out in tx.output.iter() {
185                         #[cfg(test)]
186                         for &(ref txid, ref script) in self.watched_txn.iter() {
187                                 if *script == out.script_pubkey {
188                                         if tx.txid() == *txid {
189                                                 return true;
190                                         }
191                                 }
192                         }
193                         #[cfg(not(test))]
194                         for script in self.watched_txn.iter() {
195                                 if *script == out.script_pubkey {
196                                         return true;
197                                 }
198                         }
199                 }
200                 for input in tx.input.iter() {
201                         for outpoint in self.watched_outpoints.iter() {
202                                 let &(outpoint_hash, outpoint_index) = outpoint;
203                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
204                                         return true;
205                                 }
206                         }
207                 }
208                 false
209         }
210 }
211
212 /// BlockNotifierArc is useful when you need a BlockNotifier that points to ChainListeners with
213 /// static lifetimes, e.g. when you're using lightning-net-tokio (since tokio::spawn requires
214 /// parameters with static lifetimes). Other times you can afford a reference, which is more
215 /// efficient, in which case BlockNotifierRef is a more appropriate type. Defining these type
216 /// aliases prevents issues such as overly long function definitions.
217 ///
218 /// (C-not exported) as we let clients handle any reference counting they need to do
219 pub type BlockNotifierArc = Arc<BlockNotifier<'static, Arc<ChainListener>>>;
220
221 /// BlockNotifierRef is useful when you want a BlockNotifier that points to ChainListeners
222 /// with nonstatic lifetimes. This is useful for when static lifetimes are not needed. Nonstatic
223 /// lifetimes are more efficient but less flexible, and should be used by default unless static
224 /// lifetimes are required, e.g. when you're using lightning-net-tokio (since tokio::spawn
225 /// requires parameters with static lifetimes), in which case BlockNotifierArc is a more
226 /// appropriate type. Defining these type aliases for common usages prevents issues such as
227 /// overly long function definitions.
228 pub type BlockNotifierRef<'a> = BlockNotifier<'a, &'a ChainListener>;
229
230 /// Utility for notifying listeners when blocks are connected or disconnected.
231 ///
232 /// Rather than using a plain BlockNotifier, it is preferable to use either a BlockNotifierArc
233 /// or a BlockNotifierRef for conciseness. See their documentation for more details, but essentially
234 /// you should default to using a BlockNotifierRef, and use a BlockNotifierArc instead when you
235 /// require ChainListeners with static lifetimes, such as when you're using lightning-net-tokio.
236 pub struct BlockNotifier<'a, CL: Deref + 'a>
237                 where CL::Target: ChainListener + 'a {
238         listeners: Mutex<Vec<CL>>,
239         phantom: PhantomData<&'a ()>,
240 }
241
242 impl<'a, CL: Deref + 'a> BlockNotifier<'a, CL>
243                 where CL::Target: ChainListener + 'a {
244         /// Constructs a new BlockNotifier without any listeners.
245         pub fn new() -> BlockNotifier<'a, CL> {
246                 BlockNotifier {
247                         listeners: Mutex::new(Vec::new()),
248                         phantom: PhantomData,
249                 }
250         }
251
252         /// Register the given listener to receive events.
253         pub fn register_listener(&self, listener: CL) {
254                 let mut vec = self.listeners.lock().unwrap();
255                 vec.push(listener);
256         }
257         /// Unregister the given listener to no longer
258         /// receive events.
259         ///
260         /// If the same listener is registered multiple times, unregistering
261         /// will remove ALL occurrences of that listener. Comparison is done using
262         /// the pointer returned by the Deref trait implementation.
263         ///
264         /// (C-not exported) because the equality check would always fail
265         pub fn unregister_listener(&self, listener: CL) {
266                 let mut vec = self.listeners.lock().unwrap();
267                 // item is a ref to an abstract thing that dereferences to a ChainListener,
268                 // so dereference it twice to get the ChainListener itself
269                 vec.retain(|item | !ptr::eq(&(**item), &(*listener)));
270         }
271
272         /// Notify listeners that a block was connected.
273         pub fn block_connected(&self, block: &Block, height: u32) {
274                 let txdata: Vec<_> = block.txdata.iter().enumerate().collect();
275                 let listeners = self.listeners.lock().unwrap();
276                 for listener in listeners.iter() {
277                         listener.block_connected(&block.header, &txdata, height);
278                 }
279         }
280
281         /// Notify listeners that a block was disconnected.
282         pub fn block_disconnected(&self, header: &BlockHeader, disconnected_height: u32) {
283                 let listeners = self.listeners.lock().unwrap();
284                 for listener in listeners.iter() {
285                         listener.block_disconnected(&header, disconnected_height);
286                 }
287         }
288 }
289
290 /// Utility to capture some common parts of ChainWatchInterface implementors.
291 ///
292 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
293 pub struct ChainWatchInterfaceUtil {
294         network: Network,
295         watched: Mutex<ChainWatchedUtil>,
296         reentered: AtomicUsize,
297 }
298
299 // We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
300 // only comparing a subset of fields (essentially just checking that the set of things we're
301 // watching is the same).
302 #[cfg(test)]
303 impl PartialEq for ChainWatchInterfaceUtil {
304         fn eq(&self, o: &Self) -> bool {
305                 self.network == o.network &&
306                 *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
307         }
308 }
309
310 /// Register listener
311 impl ChainWatchInterface for ChainWatchInterfaceUtil {
312         fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
313                 let mut watched = self.watched.lock().unwrap();
314                 if watched.register_tx(txid, script_pub_key) {
315                         self.reentered.fetch_add(1, Ordering::Relaxed);
316                 }
317         }
318
319         fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
320                 let mut watched = self.watched.lock().unwrap();
321                 if watched.register_outpoint(outpoint, out_script) {
322                         self.reentered.fetch_add(1, Ordering::Relaxed);
323                 }
324         }
325
326         fn watch_all_txn(&self) {
327                 let mut watched = self.watched.lock().unwrap();
328                 if watched.watch_all() {
329                         self.reentered.fetch_add(1, Ordering::Relaxed);
330                 }
331         }
332
333         fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
334                 if genesis_hash != genesis_block(self.network).header.block_hash() {
335                         return Err(ChainError::NotWatched);
336                 }
337                 Err(ChainError::NotSupported)
338         }
339
340         fn filter_block(&self, _header: &BlockHeader, txdata: &[(usize, &Transaction)]) -> Vec<usize> {
341                 let mut matched_index = Vec::new();
342                 let mut matched_txids = HashSet::new();
343                 {
344                         let watched = self.watched.lock().unwrap();
345                         for (index, transaction) in txdata.iter().enumerate() {
346                                 // A tx matches the filter if it either matches the filter directly (via
347                                 // does_match_tx_unguarded) or if it is a descendant of another matched
348                                 // transaction within the same block, which we check for in the loop.
349                                 let mut matched = self.does_match_tx_unguarded(transaction.1, &watched);
350                                 for input in transaction.1.input.iter() {
351                                         if matched || matched_txids.contains(&input.previous_output.txid) {
352                                                 matched = true;
353                                                 break;
354                                         }
355                                 }
356                                 if matched {
357                                         matched_txids.insert(transaction.1.txid());
358                                         matched_index.push(index);
359                                 }
360                         }
361                 }
362                 matched_index
363         }
364
365         fn reentered(&self) -> usize {
366                 self.reentered.load(Ordering::Relaxed)
367         }
368 }
369
370 impl ChainWatchInterfaceUtil {
371         /// Creates a new ChainWatchInterfaceUtil for the given network
372         pub fn new(network: Network) -> ChainWatchInterfaceUtil {
373                 ChainWatchInterfaceUtil {
374                         network,
375                         watched: Mutex::new(ChainWatchedUtil::new()),
376                         reentered: AtomicUsize::new(1),
377                 }
378         }
379
380         /// Checks if a given transaction matches the current filter.
381         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
382                 let watched = self.watched.lock().unwrap();
383                 self.does_match_tx_unguarded (tx, &watched)
384         }
385
386         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
387                 watched.does_match_tx(tx)
388         }
389 }
390
391 #[cfg(test)]
392 mod tests {
393         use bitcoin::blockdata::block::BlockHeader;
394         use bitcoin::blockdata::transaction::Transaction;
395         use super::{BlockNotifier, ChainListener};
396         use std::ptr;
397
398         struct TestChainListener(u8);
399
400         impl ChainListener for TestChainListener {
401                 fn block_connected(&self, _header: &BlockHeader, _txdata: &[(usize, &Transaction)], _height: u32) {}
402                 fn block_disconnected(&self, _header: &BlockHeader, _disconnected_height: u32) {}
403         }
404
405         #[test]
406         fn register_listener_test() {
407                 let block_notifier = BlockNotifier::new();
408                 assert_eq!(block_notifier.listeners.lock().unwrap().len(), 0);
409                 let listener = &TestChainListener(0);
410                 block_notifier.register_listener(listener as &ChainListener);
411                 let vec = block_notifier.listeners.lock().unwrap();
412                 assert_eq!(vec.len(), 1);
413                 let item = vec.first().unwrap();
414                 assert!(ptr::eq(&(**item), listener));
415         }
416
417         #[test]
418         fn unregister_single_listener_test() {
419                 let block_notifier = BlockNotifier::new();
420                 let listener1 = &TestChainListener(1);
421                 let listener2 = &TestChainListener(2);
422                 block_notifier.register_listener(listener1 as &ChainListener);
423                 block_notifier.register_listener(listener2 as &ChainListener);
424                 let vec = block_notifier.listeners.lock().unwrap();
425                 assert_eq!(vec.len(), 2);
426                 drop(vec);
427                 block_notifier.unregister_listener(listener1);
428                 let vec = block_notifier.listeners.lock().unwrap();
429                 assert_eq!(vec.len(), 1);
430                 let item = vec.first().unwrap();
431                 assert!(ptr::eq(&(**item), listener2));
432         }
433
434         #[test]
435         fn unregister_multiple_of_the_same_listeners_test() {
436                 let block_notifier = BlockNotifier::new();
437                 let listener1 = &TestChainListener(1);
438                 let listener2 = &TestChainListener(2);
439                 block_notifier.register_listener(listener1 as &ChainListener);
440                 block_notifier.register_listener(listener1 as &ChainListener);
441                 block_notifier.register_listener(listener2 as &ChainListener);
442                 let vec = block_notifier.listeners.lock().unwrap();
443                 assert_eq!(vec.len(), 3);
444                 drop(vec);
445                 block_notifier.unregister_listener(listener1);
446                 let vec = block_notifier.listeners.lock().unwrap();
447                 assert_eq!(vec.len(), 1);
448                 let item = vec.first().unwrap();
449                 assert!(ptr::eq(&(**item), listener2));
450         }
451 }