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