Update to rust-secp256k1 v0.11 and rust-bitcoin v0.14
[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::util::hash::Sha256dHash;
5 use util::logger::Logger;
6 use std::sync::{Mutex,Weak,MutexGuard,Arc};
7 use std::sync::atomic::{AtomicUsize, Ordering};
8
9 /// An interface to request notification of certain scripts as they appear the
10 /// chain.
11 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
12 /// called from inside the library in response to ChainListener events, P2P events, or timer
13 /// events).
14 pub trait ChainWatchInterface: Sync + Send {
15         /// Provides a scriptPubKey which much be watched for.
16         fn install_watch_script(&self, script_pub_key: &Script);
17
18         /// Provides an outpoint which must be watched for, providing any transactions which spend the
19         /// given outpoint.
20         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
21
22         /// Indicates that a listener needs to see all transactions.
23         fn watch_all_txn(&self);
24
25         fn register_listener(&self, listener: Weak<ChainListener>);
26         //TODO: unregister
27 }
28
29 /// An interface to send a transaction to the Bitcoin network.
30 pub trait BroadcasterInterface: Sync + Send {
31         /// Sends a transaction out to (hopefully) be mined.
32         fn broadcast_transaction(&self, tx: &Transaction);
33 }
34
35 /// A trait indicating a desire to listen for events from the chain
36 pub trait ChainListener: Sync + Send {
37         /// Notifies a listener that a block was connected.
38         /// Note that if a new script/transaction is watched during a block_connected call, the block
39         /// *must* be re-scanned with the new script/transaction and block_connected should be called
40         /// again with the same header and (at least) the new transactions.
41         /// This also means those counting confirmations using block_connected callbacks should watch
42         /// for duplicate headers and not count them towards confirmations!
43         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
44         /// Notifies a listener that a block was disconnected.
45         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
46         fn block_disconnected(&self, header: &BlockHeader);
47 }
48
49 pub enum ConfirmationTarget {
50         Background,
51         Normal,
52         HighPriority,
53 }
54
55 /// A trait which should be implemented to provide feerate information on a number of time
56 /// horizons.
57 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
58 /// called from inside the library in response to ChainListener events, P2P events, or timer
59 /// events).
60 pub trait FeeEstimator: Sync + Send {
61         /// Gets estimated satoshis of fee required per 1000 Weight-Units. This translates to:
62         ///  * satoshis-per-byte * 250
63         ///  * ceil(satoshis-per-kbyte / 4)
64         /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
65         /// don't put us below 1 satoshi-per-byte).
66         fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
67 }
68
69 /// Utility to capture some common parts of ChainWatchInterface implementors.
70 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
71 pub struct ChainWatchInterfaceUtil {
72         watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
73         listeners: Mutex<Vec<Weak<ChainListener>>>,
74         reentered: AtomicUsize,
75         logger: Arc<Logger>,
76 }
77
78 /// Register listener
79 impl ChainWatchInterface for ChainWatchInterfaceUtil {
80         fn install_watch_script(&self, script_pub_key: &Script) {
81                 let mut watched = self.watched.lock().unwrap();
82                 watched.0.push(script_pub_key.clone());
83                 self.reentered.fetch_add(1, Ordering::Relaxed);
84         }
85
86         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), _out_script: &Script) {
87                 let mut watched = self.watched.lock().unwrap();
88                 watched.1.push(outpoint);
89                 self.reentered.fetch_add(1, Ordering::Relaxed);
90         }
91
92         fn watch_all_txn(&self) {
93                 let mut watched = self.watched.lock().unwrap();
94                 watched.2 = true;
95                 self.reentered.fetch_add(1, Ordering::Relaxed);
96         }
97
98         fn register_listener(&self, listener: Weak<ChainListener>) {
99                 let mut vec = self.listeners.lock().unwrap();
100                 vec.push(listener);
101         }
102 }
103
104 impl ChainWatchInterfaceUtil {
105         pub fn new(logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
106                 ChainWatchInterfaceUtil {
107                         watched: Mutex::new((Vec::new(), Vec::new(), false)),
108                         listeners: Mutex::new(Vec::new()),
109                         reentered: AtomicUsize::new(1),
110                         logger: logger,
111                 }
112         }
113
114         /// Notify listeners that a block was connected given a full, unfiltered block.
115         /// Handles re-scanning the block and calling block_connected again if listeners register new
116         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
117         pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
118                 let mut reentered = true;
119                 while reentered {
120                         let mut matched = Vec::new();
121                         let mut matched_index = Vec::new();
122                         {
123                                 let watched = self.watched.lock().unwrap();
124                                 for (index, transaction) in block.txdata.iter().enumerate() {
125                                         if self.does_match_tx_unguarded(transaction, &watched) {
126                                                 matched.push(transaction);
127                                                 matched_index.push(index as u32);
128                                         }
129                                 }
130                         }
131                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
132                 }
133         }
134
135         /// Notify listeners that a block was disconnected.
136         pub fn block_disconnected(&self, header: &BlockHeader) {
137                 let listeners = self.listeners.lock().unwrap().clone();
138                 for listener in listeners.iter() {
139                         match listener.upgrade() {
140                                 Some(arc) => arc.block_disconnected(header),
141                                 None => ()
142                         }
143                 }
144         }
145
146         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
147         /// block which matched the filter (probably using does_match_tx).
148         /// Returns true if notified listeners registered additional watch data (implying that the
149         /// block must be re-scanned and this function called again prior to further block_connected
150         /// calls, see ChainListener::block_connected for more info).
151         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
152                 let last_seen = self.reentered.load(Ordering::Relaxed);
153
154                 let listeners = self.listeners.lock().unwrap().clone();
155                 for listener in listeners.iter() {
156                         match listener.upgrade() {
157                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
158                                 None => ()
159                         }
160                 }
161                 return last_seen != self.reentered.load(Ordering::Relaxed);
162         }
163
164         /// Checks if a given transaction matches the current filter.
165         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
166                 let watched = self.watched.lock().unwrap();
167                 self.does_match_tx_unguarded (tx, &watched)
168         }
169
170         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
171                 if watched.2 {
172                         return true;
173                 }
174                 for out in tx.output.iter() {
175                         for script in watched.0.iter() {
176                                 if script[..] == out.script_pubkey[..] {
177                                         return true;
178                                 }
179                         }
180                 }
181                 for input in tx.input.iter() {
182                         for outpoint in watched.1.iter() {
183                                 let &(outpoint_hash, outpoint_index) = outpoint;
184                                 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
185                                         return true;
186                                 }
187                         }
188                 }
189                 false
190         }
191 }