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