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