Merge pull request #11 from tamasblummer/chaininterface (squashed)
[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));
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 connected Bitcoin peers.
29 /// This is for final settlement. An error might indicate that no peers can be reached or
30 /// that peers rejected the transaction.
31 pub trait BroadcasterInterface: Sync + Send {
32         /// Sends a transaction out to (hopefully) be mined
33         fn broadcast_transaction(&self, tx: &Transaction);
34 }
35
36 /// A trait indicating a desire to listen for events from the chain
37 pub trait ChainListener: Sync + Send {
38         /// Notifies a listener that a block was connected.
39         /// Note that if a new script/transaction is watched during a block_connected call, the block
40         /// *must* be re-scanned with the new script/transaction and block_connected should be called
41         /// again with the same header and (at least) the new transactions.
42         /// This also means those counting confirmations using block_connected callbacks should watch
43         /// for duplicate headers and not count them towards confirmations!
44         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
45         /// Notifies a listener that a block was disconnected.
46         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
47         fn block_disconnected(&self, header: &BlockHeader);
48 }
49
50 pub enum ConfirmationTarget {
51         Background,
52         Normal,
53         HighPriority,
54 }
55
56 /// A trait which should be implemented to provide feerate information on a number of time
57 /// horizons.
58 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
59 /// called from inside the library in response to ChainListener events, P2P events, or timer
60 /// events).
61 pub trait FeeEstimator: Sync + Send {
62         fn get_est_sat_per_vbyte(&self, confirmation_target: ConfirmationTarget) -> u64;
63 }
64
65 /// Utility to capture some common parts of ChainWatchInterface implementors.
66 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
67 pub struct ChainWatchInterfaceUtil {
68         watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
69         listeners: Mutex<Vec<Weak<ChainListener>>>,
70         reentered: AtomicUsize
71 }
72
73 /// Register listener
74 impl ChainWatchInterface for ChainWatchInterfaceUtil {
75         fn install_watch_script(&self, script_pub_key: Script) {
76                 let mut watched = self.watched.lock().unwrap();
77                 watched.0.push(Script::from(script_pub_key));
78                 self.reentered.fetch_add(1, Ordering::Relaxed);
79         }
80
81         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
82                 let mut watched = self.watched.lock().unwrap();
83                 watched.1.push(outpoint);
84                 self.reentered.fetch_add(1, Ordering::Relaxed);
85         }
86
87         fn watch_all_txn(&self) {
88                 let mut watched = self.watched.lock().unwrap();
89                 watched.2 = true;
90                 self.reentered.fetch_add(1, Ordering::Relaxed);
91         }
92
93         fn register_listener(&self, listener: Weak<ChainListener>) {
94                 let mut vec = self.listeners.lock().unwrap();
95                 vec.push(listener);
96         }
97 }
98
99 impl ChainWatchInterfaceUtil {
100         pub fn new() -> ChainWatchInterfaceUtil {
101                 ChainWatchInterfaceUtil {
102                         watched: Mutex::new((Vec::new(), Vec::new(), false)),
103                         listeners: Mutex::new(Vec::new()),
104                         reentered: AtomicUsize::new(1)
105                 }
106         }
107
108         /// notify listener that a block was connected
109         /// notification will repeat if notified listener register new listeners
110         pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
111                 let mut reentered = true;
112                 while reentered {
113                         let mut matched = Vec::new();
114                         let mut matched_index = Vec::new();
115                         {
116                                 let watched = self.watched.lock().unwrap();
117                                 for (index, transaction) in block.txdata.iter().enumerate() {
118                                         if self.does_match_tx_unguarded(transaction, &watched) {
119                                                 matched.push(transaction);
120                                                 matched_index.push(index as u32);
121                                         }
122                                 }
123                         }
124                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
125                 }
126         }
127
128         /// notify listener that a block was disconnected
129         pub fn block_disconnected(&self, header: &BlockHeader) {
130                 let listeners = self.listeners.lock().unwrap().clone();
131                 for listener in listeners.iter() {
132                         match listener.upgrade() {
133                                 Some(arc) => arc.block_disconnected(header),
134                                 None => ()
135                         }
136                 }
137         }
138
139         /// call listeners for connected blocks if they are still around.
140         /// returns true if notified listeners registered additional listener
141         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
142                 let last_seen = self.reentered.load(Ordering::Relaxed);
143
144                 let listeners = self.listeners.lock().unwrap().clone();
145                 for listener in listeners.iter() {
146                         match listener.upgrade() {
147                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
148                                 None => ()
149                         }
150                 }
151                 return last_seen != self.reentered.load(Ordering::Relaxed);
152         }
153
154         /// Checks if a given transaction matches the current filter
155         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
156                 let watched = self.watched.lock().unwrap();
157                 self.does_match_tx_unguarded (tx, &watched)
158         }
159
160         fn does_match_tx_unguarded (&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
161                 if watched.2 {
162                         return true;
163                 }
164                 for out in tx.output.iter() {
165                         for script in watched.0.iter() {
166                                 if script[..] == out.script_pubkey[..] {
167                                         return true;
168                                 }
169                         }
170                 }
171                 for input in tx.input.iter() {
172                         for outpoint in watched.1.iter() {
173                                 let &(outpoint_hash, outpoint_index) = outpoint;
174                                 if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {
175                                         return true;
176                                 }
177                         }
178                 }
179                 false
180         }
181 }