Ensure the funding transaction is registered to be monitored
[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         fn get_est_sat_per_vbyte(&self, confirmation_target: ConfirmationTarget) -> u64;
61 }
62
63 /// Utility to capture some common parts of ChainWatchInterface implementors.
64 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
65 pub struct ChainWatchInterfaceUtil {
66         watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
67         listeners: Mutex<Vec<Weak<ChainListener>>>,
68         reentered: AtomicUsize
69 }
70
71 /// Register listener
72 impl ChainWatchInterface for ChainWatchInterfaceUtil {
73         fn install_watch_script(&self, script_pub_key: &Script) {
74                 let mut watched = self.watched.lock().unwrap();
75                 watched.0.push(script_pub_key.clone());
76                 self.reentered.fetch_add(1, Ordering::Relaxed);
77         }
78
79         fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), _out_script: &Script) {
80                 let mut watched = self.watched.lock().unwrap();
81                 watched.1.push(outpoint);
82                 self.reentered.fetch_add(1, Ordering::Relaxed);
83         }
84
85         fn watch_all_txn(&self) {
86                 let mut watched = self.watched.lock().unwrap();
87                 watched.2 = true;
88                 self.reentered.fetch_add(1, Ordering::Relaxed);
89         }
90
91         fn register_listener(&self, listener: Weak<ChainListener>) {
92                 let mut vec = self.listeners.lock().unwrap();
93                 vec.push(listener);
94         }
95 }
96
97 impl ChainWatchInterfaceUtil {
98         pub fn new() -> ChainWatchInterfaceUtil {
99                 ChainWatchInterfaceUtil {
100                         watched: Mutex::new((Vec::new(), Vec::new(), false)),
101                         listeners: Mutex::new(Vec::new()),
102                         reentered: AtomicUsize::new(1)
103                 }
104         }
105
106         /// Notify listeners that a block was connected given a full, unfiltered block.
107         /// Handles re-scanning the block and calling block_connected again if listeners register new
108         /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
109         pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
110                 let mut reentered = true;
111                 while reentered {
112                         let mut matched = Vec::new();
113                         let mut matched_index = Vec::new();
114                         {
115                                 let watched = self.watched.lock().unwrap();
116                                 for (index, transaction) in block.txdata.iter().enumerate() {
117                                         if self.does_match_tx_unguarded(transaction, &watched) {
118                                                 matched.push(transaction);
119                                                 matched_index.push(index as u32);
120                                         }
121                                 }
122                         }
123                         reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
124                 }
125         }
126
127         /// Notify listeners that a block was disconnected.
128         pub fn block_disconnected(&self, header: &BlockHeader) {
129                 let listeners = self.listeners.lock().unwrap().clone();
130                 for listener in listeners.iter() {
131                         match listener.upgrade() {
132                                 Some(arc) => arc.block_disconnected(header),
133                                 None => ()
134                         }
135                 }
136         }
137
138         /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
139         /// block which matched the filter (probably using does_match_tx).
140         /// Returns true if notified listeners registered additional watch data (implying that the
141         /// block must be re-scanned and this function called again prior to further block_connected
142         /// calls, see ChainListener::block_connected for more info).
143         pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
144                 let last_seen = self.reentered.load(Ordering::Relaxed);
145
146                 let listeners = self.listeners.lock().unwrap().clone();
147                 for listener in listeners.iter() {
148                         match listener.upgrade() {
149                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
150                                 None => ()
151                         }
152                 }
153                 return last_seen != self.reentered.load(Ordering::Relaxed);
154         }
155
156         /// Checks if a given transaction matches the current filter.
157         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
158                 let watched = self.watched.lock().unwrap();
159                 self.does_match_tx_unguarded (tx, &watched)
160         }
161
162         fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
163                 if watched.2 {
164                         return true;
165                 }
166                 for out in tx.output.iter() {
167                         for script in watched.0.iter() {
168                                 if script[..] == out.script_pubkey[..] {
169                                         return true;
170                                 }
171                         }
172                 }
173                 for input in tx.input.iter() {
174                         for outpoint in watched.1.iter() {
175                                 let &(outpoint_hash, outpoint_index) = outpoint;
176                                 if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {
177                                         return true;
178                                 }
179                         }
180                 }
181                 false
182         }
183 }