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