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