7b5e0d0749832a7cf2ffcfcd560156d085fd53f7
[rust-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, transactio 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, Sha256dHash};
12 use bitcoin::network::constants::Network;
13
14 use util::logger::Logger;
15
16 use std::sync::{Mutex,Weak,MutexGuard,Arc};
17 use std::sync::atomic::{AtomicUsize, Ordering};
18 use std::collections::HashSet;
19
20 /// Used to give chain error details upstream
21 pub enum ChainError {
22         /// Client doesn't support UTXO lookup (but the chain hash matches our genesis block hash)
23         NotSupported,
24         /// Chain isn't the one watched
25         NotWatched,
26         /// Tx doesn't exist or is unconfirmed
27         UnknownTx,
28 }
29
30 /// An interface to request notification of certain scripts as they appear the
31 /// chain.
32 ///
33 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
34 /// called from inside the library in response to ChainListener events, P2P events, or timer
35 /// events).
36 pub trait ChainWatchInterface: Sync + Send {
37         /// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
38         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script);
39
40         /// Provides an outpoint which must be watched for, providing any transactions which spend the
41         /// given outpoint.
42         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
43
44         /// Indicates that a listener needs to see all transactions.
45         fn watch_all_txn(&self);
46
47         /// Register the given listener to receive events. Only a weak pointer is provided and the
48         /// registration should be freed once that pointer expires.
49         fn register_listener(&self, listener: Weak<ChainListener>);
50         //TODO: unregister
51
52         /// Gets the script and value in satoshis for a given unspent transaction output given a
53         /// short_channel_id (aka unspent_tx_output_identier). For BTC/tBTC channels the top three
54         /// bytes are the block height, the next 3 the transaction index within the block, and the
55         /// final two the output within the transaction.
56         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError>;
57 }
58
59 /// An interface to send a transaction to the Bitcoin network.
60 pub trait BroadcasterInterface: Sync + Send {
61         /// Sends a transaction out to (hopefully) be mined.
62         fn broadcast_transaction(&self, tx: &Transaction);
63 }
64
65 /// A trait indicating a desire to listen for events from the chain
66 pub trait ChainListener: Sync + Send {
67         /// Notifies a listener that a block was connected.
68         /// Note that if a new transaction/outpoint is watched during a block_connected call, the block
69         /// *must* be re-scanned with the new transaction/outpoints and block_connected should be
70         /// called again with the same header and (at least) the new transactions.
71         ///
72         /// Note that if non-new transaction/outpoints may be registered during a call, a second call
73         /// *must not* happen.
74         ///
75         /// This also means those counting confirmations using block_connected callbacks should watch
76         /// for duplicate headers and not count them towards confirmations!
77         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
78         /// Notifies a listener that a block was disconnected.
79         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
80         fn block_disconnected(&self, header: &BlockHeader);
81 }
82
83 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
84 /// estimation.
85 pub enum ConfirmationTarget {
86         /// We are happy with this transaction confirming slowly when feerate drops some.
87         Background,
88         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
89         Normal,
90         /// We'd like this transaction to confirm in the next few blocks.
91         HighPriority,
92 }
93
94 /// A trait which should be implemented to provide feerate information on a number of time
95 /// horizons.
96 ///
97 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
98 /// called from inside the library in response to ChainListener events, P2P events, or timer
99 /// events).
100 pub trait FeeEstimator: Sync + Send {
101         /// Gets estimated satoshis of fee required per 1000 Weight-Units.
102         ///
103         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
104         /// don't put us below 1 satoshi-per-byte).
105         ///
106         /// This translates to:
107         ///  * satoshis-per-byte * 250
108         ///  * ceil(satoshis-per-kbyte / 4)
109         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
110 }
111
112 /// Utility for tracking registered txn/outpoints and checking for matches
113 pub struct ChainWatchedUtil {
114         watch_all: bool,
115
116         // We are more conservative in matching during testing to ensure everything matches *exactly*,
117         // even though during normal runtime we take more optimized match approaches...
118         #[cfg(test)]
119         watched_txn: HashSet<(Sha256dHash, Script)>,
120         #[cfg(not(test))]
121         watched_txn: HashSet<Script>,
122
123         watched_outpoints: HashSet<(Sha256dHash, u32)>,
124 }
125
126 impl ChainWatchedUtil {
127         /// Constructs an empty (watches nothing) ChainWatchedUtil
128         pub fn new() -> Self {
129                 Self {
130                         watch_all: false,
131                         watched_txn: HashSet::new(),
132                         watched_outpoints: HashSet::new(),
133                 }
134         }
135
136         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
137         /// been watching for it.
138         pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
139                 if self.watch_all { return false; }
140                 #[cfg(test)]
141                 {
142                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
143                 }
144                 #[cfg(not(test))]
145                 {
146                         let _tx_unused = txid; // Its used in cfg(test), though
147                         self.watched_txn.insert(script_pub_key.clone())
148                 }
149         }
150
151         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
152         /// we'd already been watching for it
153         pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
154                 if self.watch_all { return false; }
155                 self.watched_outpoints.insert(outpoint)
156         }
157
158         /// Sets us to match all transactions, returning true if this is a new setting anf false if
159         /// we'd already been set to match everything.
160         pub fn watch_all(&mut self) -> bool {
161                 if self.watch_all { return false; }
162                 self.watch_all = true;
163                 true
164         }
165
166         /// Checks if a given transaction matches the current filter.
167         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
168                 if self.watch_all {
169                         return true;
170                 }
171                 for out in tx.output.iter() {
172                         #[cfg(test)]
173                         for &(ref txid, ref script) in self.watched_txn.iter() {
174                                 if *script == out.script_pubkey {
175                                         if tx.txid() == *txid {
176                                                 return true;
177                                         }
178                                 }
179                         }
180                         #[cfg(not(test))]
181                         for script in self.watched_txn.iter() {
182                                 if *script == out.script_pubkey {
183                                         return true;
184                                 }
185                         }
186                 }
187                 for input in tx.input.iter() {
188                         for outpoint in self.watched_outpoints.iter() {
189                                 let &(outpoint_hash, outpoint_index) = outpoint;
190                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
191                                         return true;
192                                 }
193                         }
194                 }
195                 false
196         }
197 }
198
199 /// Utility to capture some common parts of ChainWatchInterface implementors.
200 ///
201 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
202 pub struct ChainWatchInterfaceUtil {
203         network: Network,
204         watched: Mutex<ChainWatchedUtil>,
205         listeners: Mutex<Vec<Weak<ChainListener>>>,
206         reentered: AtomicUsize,
207         logger: Arc<Logger>,
208 }
209
210 /// Register listener
211 impl ChainWatchInterface for ChainWatchInterfaceUtil {
212         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
213                 let mut watched = self.watched.lock().unwrap();
214                 if watched.register_tx(txid, script_pub_key) {
215                         self.reentered.fetch_add(1, Ordering::Relaxed);
216                 }
217         }
218
219         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
220                 let mut watched = self.watched.lock().unwrap();
221                 if watched.register_outpoint(outpoint, out_script) {
222                         self.reentered.fetch_add(1, Ordering::Relaxed);
223                 }
224         }
225
226         fn watch_all_txn(&self) {
227                 let mut watched = self.watched.lock().unwrap();
228                 if watched.watch_all() {
229                         self.reentered.fetch_add(1, Ordering::Relaxed);
230                 }
231         }
232
233         fn register_listener(&self, listener: Weak<ChainListener>) {
234                 let mut vec = self.listeners.lock().unwrap();
235                 vec.push(listener);
236         }
237
238         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
239                 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
240                         return Err(ChainError::NotWatched);
241                 }
242                 Err(ChainError::NotSupported)
243         }
244 }
245
246 impl ChainWatchInterfaceUtil {
247         /// Creates a new ChainWatchInterfaceUtil for the given network
248         pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
249                 ChainWatchInterfaceUtil {
250                         network: network,
251                         watched: Mutex::new(ChainWatchedUtil::new()),
252                         listeners: Mutex::new(Vec::new()),
253                         reentered: AtomicUsize::new(1),
254                         logger: logger,
255                 }
256         }
257
258         /// Notify listeners that a block was connected given a full, unfiltered block.
259         ///
260         /// Handles re-scanning the block and calling block_connected again if listeners register new
261         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
262         pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
263                 let mut reentered = true;
264                 while reentered {
265                         let mut matched = Vec::new();
266                         let mut matched_index = Vec::new();
267                         {
268                                 let watched = self.watched.lock().unwrap();
269                                 for (index, transaction) in block.txdata.iter().enumerate() {
270                                         if self.does_match_tx_unguarded(transaction, &watched) {
271                                                 matched.push(transaction);
272                                                 matched_index.push(index as u32);
273                                         }
274                                 }
275                         }
276                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
277                 }
278         }
279
280         /// Notify listeners that a block was disconnected.
281         pub fn block_disconnected(&self, header: &BlockHeader) {
282                 let listeners = self.listeners.lock().unwrap().clone();
283                 for listener in listeners.iter() {
284                         match listener.upgrade() {
285                                 Some(arc) => arc.block_disconnected(header),
286                                 None => ()
287                         }
288                 }
289         }
290
291         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
292         /// block which matched the filter (probably using does_match_tx).
293         ///
294         /// Returns true if notified listeners registered additional watch data (implying that the
295         /// block must be re-scanned and this function called again prior to further block_connected
296         /// calls, see ChainListener::block_connected for more info).
297         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
298                 let last_seen = self.reentered.load(Ordering::Relaxed);
299
300                 let listeners = self.listeners.lock().unwrap().clone();
301                 for listener in listeners.iter() {
302                         match listener.upgrade() {
303                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
304                                 None => ()
305                         }
306                 }
307                 return last_seen != self.reentered.load(Ordering::Relaxed);
308         }
309
310         /// Checks if a given transaction matches the current filter.
311         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
312                 let watched = self.watched.lock().unwrap();
313                 self.does_match_tx_unguarded (tx, &watched)
314         }
315
316         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
317                 watched.does_match_tx(tx)
318         }
319 }