Document ConfirmationTarget a little bit (closes #101)
[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 /// An enum that represents the speed at which we want a transaction to confirm used for feerate
74 /// estimation.
75 pub enum ConfirmationTarget {
76         /// We are happy with this transaction confirming slowly when feerate drops some.
77         Background,
78         /// We'd like this transaction to confirm without major delay, but 12-18 blocks is fine.
79         Normal,
80         /// We'd like this transaction to confirm in the next few blocks.
81         HighPriority,
82 }
83
84 /// A trait which should be implemented to provide feerate information on a number of time
85 /// horizons.
86 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
87 /// called from inside the library in response to ChainListener events, P2P events, or timer
88 /// events).
89 pub trait FeeEstimator: Sync + Send {
90         /// Gets estimated satoshis of fee required per 1000 Weight-Units. This translates to:
91         ///  * satoshis-per-byte * 250
92         ///  * ceil(satoshis-per-kbyte / 4)
93         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
94         /// don't put us below 1 satoshi-per-byte).
95         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
96 }
97
98 /// Utility for tracking registered txn/outpoints and checking for matches
99 pub struct ChainWatchedUtil {
100         watch_all: bool,
101
102         // We are more conservative in matching during testing to ensure everything matches *exactly*,
103         // even though during normal runtime we take more optimized match approaches...
104         #[cfg(test)]
105         watched_txn: HashSet<(Sha256dHash, Script)>,
106         #[cfg(not(test))]
107         watched_txn: HashSet<Script>,
108
109         watched_outpoints: HashSet<(Sha256dHash, u32)>,
110 }
111
112 impl ChainWatchedUtil {
113         /// Constructs an empty (watches nothing) ChainWatchedUtil
114         pub fn new() -> Self {
115                 Self {
116                         watch_all: false,
117                         watched_txn: HashSet::new(),
118                         watched_outpoints: HashSet::new(),
119                 }
120         }
121
122         /// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
123         /// been watching for it.
124         pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
125                 if self.watch_all { return false; }
126                 #[cfg(test)]
127                 {
128                         self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
129                 }
130                 #[cfg(not(test))]
131                 {
132                         let _tx_unused = txid; // Its used in cfg(test), though
133                         self.watched_txn.insert(script_pub_key.clone())
134                 }
135         }
136
137         /// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
138         /// we'd already been watching for it
139         pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
140                 if self.watch_all { return false; }
141                 self.watched_outpoints.insert(outpoint)
142         }
143
144         /// Sets us to match all transactions, returning true if this is a new setting anf false if
145         /// we'd already been set to match everything.
146         pub fn watch_all(&mut self) -> bool {
147                 if self.watch_all { return false; }
148                 self.watch_all = true;
149                 true
150         }
151
152         /// Checks if a given transaction matches the current filter.
153         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
154                 if self.watch_all {
155                         return true;
156                 }
157                 for out in tx.output.iter() {
158                         #[cfg(test)]
159                         for &(ref txid, ref script) in self.watched_txn.iter() {
160                                 if *script == out.script_pubkey {
161                                         if tx.txid() == *txid {
162                                                 return true;
163                                         }
164                                 }
165                         }
166                         #[cfg(not(test))]
167                         for script in self.watched_txn.iter() {
168                                 if *script == out.script_pubkey {
169                                         return true;
170                                 }
171                         }
172                 }
173                 for input in tx.input.iter() {
174                         for outpoint in self.watched_outpoints.iter() {
175                                 let &(outpoint_hash, outpoint_index) = outpoint;
176                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
177                                         return true;
178                                 }
179                         }
180                 }
181                 false
182         }
183 }
184
185 /// Utility to capture some common parts of ChainWatchInterface implementors.
186 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
187 pub struct ChainWatchInterfaceUtil {
188         network: Network,
189         watched: Mutex<ChainWatchedUtil>,
190         listeners: Mutex<Vec<Weak<ChainListener>>>,
191         reentered: AtomicUsize,
192         logger: Arc<Logger>,
193 }
194
195 /// Register listener
196 impl ChainWatchInterface for ChainWatchInterfaceUtil {
197         fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
198                 let mut watched = self.watched.lock().unwrap();
199                 if watched.register_tx(txid, script_pub_key) {
200                         self.reentered.fetch_add(1, Ordering::Relaxed);
201                 }
202         }
203
204         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
205                 let mut watched = self.watched.lock().unwrap();
206                 if watched.register_outpoint(outpoint, out_script) {
207                         self.reentered.fetch_add(1, Ordering::Relaxed);
208                 }
209         }
210
211         fn watch_all_txn(&self) {
212                 let mut watched = self.watched.lock().unwrap();
213                 if watched.watch_all() {
214                         self.reentered.fetch_add(1, Ordering::Relaxed);
215                 }
216         }
217
218         fn register_listener(&self, listener: Weak<ChainListener>) {
219                 let mut vec = self.listeners.lock().unwrap();
220                 vec.push(listener);
221         }
222
223         fn get_chain_utxo(&self, genesis_hash: Sha256dHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
224                 if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
225                         return Err(ChainError::NotWatched);
226                 }
227                 Err(ChainError::NotSupported)
228         }
229 }
230
231 impl ChainWatchInterfaceUtil {
232         pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
233                 ChainWatchInterfaceUtil {
234                         network: network,
235                         watched: Mutex::new(ChainWatchedUtil::new()),
236                         listeners: Mutex::new(Vec::new()),
237                         reentered: AtomicUsize::new(1),
238                         logger: logger,
239                 }
240         }
241
242         /// Notify listeners that a block was connected given a full, unfiltered block.
243         /// Handles re-scanning the block and calling block_connected again if listeners register new
244         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
245         pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
246                 let mut reentered = true;
247                 while reentered {
248                         let mut matched = Vec::new();
249                         let mut matched_index = Vec::new();
250                         {
251                                 let watched = self.watched.lock().unwrap();
252                                 for (index, transaction) in block.txdata.iter().enumerate() {
253                                         if self.does_match_tx_unguarded(transaction, &watched) {
254                                                 matched.push(transaction);
255                                                 matched_index.push(index as u32);
256                                         }
257                                 }
258                         }
259                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
260                 }
261         }
262
263         /// Notify listeners that a block was disconnected.
264         pub fn block_disconnected(&self, header: &BlockHeader) {
265                 let listeners = self.listeners.lock().unwrap().clone();
266                 for listener in listeners.iter() {
267                         match listener.upgrade() {
268                                 Some(arc) => arc.block_disconnected(header),
269                                 None => ()
270                         }
271                 }
272         }
273
274         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
275         /// block which matched the filter (probably using does_match_tx).
276         /// Returns true if notified listeners registered additional watch data (implying that the
277         /// block must be re-scanned and this function called again prior to further block_connected
278         /// calls, see ChainListener::block_connected for more info).
279         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
280                 let last_seen = self.reentered.load(Ordering::Relaxed);
281
282                 let listeners = self.listeners.lock().unwrap().clone();
283                 for listener in listeners.iter() {
284                         match listener.upgrade() {
285                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
286                                 None => ()
287                         }
288                 }
289                 return last_seen != self.reentered.load(Ordering::Relaxed);
290         }
291
292         /// Checks if a given transaction matches the current filter.
293         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
294                 let watched = self.watched.lock().unwrap();
295                 self.does_match_tx_unguarded (tx, &watched)
296         }
297
298         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
299                 watched.does_match_tx(tx)
300         }
301 }