ad298ce94db35eb4a29bec7c11fc884e6a8cf8af
[rust-lightning] / src / chain / chaininterface.rs
1 use bitcoin::blockdata::block::BlockHeader;
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::script::Script;
4 use bitcoin::util::hash::Sha256dHash;
5
6 use std::sync::{Weak,Mutex};
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         /// Sends a transaction out to (hopefully) be mined
25         fn broadcast_transaction(&self, tx: &Transaction);
26
27         fn register_listener(&self, listener: Weak<ChainListener>);
28         //TODO: unregister
29 }
30
31 /// A trait indicating a desire to listen for events from the chain
32 pub trait ChainListener: Sync + Send {
33         /// Notifies a listener that a block was connected.
34         /// Note that if a new script/transaction is watched during a block_connected call, the block
35         /// *must* be re-scanned with the new script/transaction and block_connected should be called
36         /// again with the same header and (at least) the new transactions.
37         /// This also means those counting confirmations using block_connected callbacks should watch
38         /// for duplicate headers and not count them towards confirmations!
39         fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
40         /// Notifies a listener that a block was disconnected.
41         /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
42         fn block_disconnected(&self, header: &BlockHeader);
43 }
44
45 pub enum ConfirmationTarget {
46         Background,
47         Normal,
48         HighPriority,
49 }
50
51 /// A trait which should be implemented to provide feerate information on a number of time
52 /// horizons.
53 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
54 /// called from inside the library in response to ChainListener events, P2P events, or timer
55 /// events).
56 pub trait FeeEstimator: Sync + Send {
57         fn get_est_sat_per_vbyte(&self, ConfirmationTarget) -> u64;
58 }
59
60 /// Utility to capture some common parts of ChainWatchInterface implementors.
61 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
62 pub struct ChainWatchInterfaceUtil {
63         watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
64         listeners: Mutex<Vec<Weak<ChainListener>>>,
65 }
66
67 impl ChainWatchInterfaceUtil {
68         pub fn new() -> ChainWatchInterfaceUtil {
69                 ChainWatchInterfaceUtil {
70                         watched: Mutex::new((Vec::new(), Vec::new(), false)),
71                         listeners: Mutex::new(Vec::new()),
72                 }
73         }
74
75         pub fn install_watch_script(&self, spk: Script) {
76                 let mut watched = self.watched.lock().unwrap();
77                 watched.0.push(Script::from(spk));
78         }
79
80         pub fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
81                 let mut watched = self.watched.lock().unwrap();
82                 watched.1.push(outpoint);
83         }
84
85         pub fn watch_all_txn(&self) { //TODO: refcnt this?
86                 let mut watched = self.watched.lock().unwrap();
87                 watched.2 = true;
88         }
89
90         pub fn register_listener(&self, listener: Weak<ChainListener>) {
91                 let mut vec = self.listeners.lock().unwrap();
92                 vec.push(listener);
93         }
94
95         pub fn do_call_block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
96                 let listeners = self.listeners.lock().unwrap().clone();
97                 for listener in listeners.iter() {
98                         match listener.upgrade() {
99                                 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
100                                 None => ()
101                         }
102                 }
103         }
104
105         pub fn do_call_block_disconnected(&self, header: &BlockHeader) {
106                 let listeners = self.listeners.lock().unwrap().clone();
107                 for listener in listeners.iter() {
108                         match listener.upgrade() {
109                                 Some(arc) => arc.block_disconnected(header),
110                                 None => ()
111                         }
112                 }
113         }
114
115         /// Checks if a given transaction matches the current filter
116         pub fn does_match_tx(&self, tx: &Transaction) -> bool {
117                 let watched = self.watched.lock().unwrap();
118                 if watched.2 {
119                         return true;
120                 }
121                 for out in tx.output.iter() {
122                         for script in watched.0.iter() {
123                                 if script[..] == out.script_pubkey[..] {
124                                         return true;
125                                 }
126                         }
127                 }
128                 for input in tx.input.iter() {
129                         for outpoint in watched.1.iter() {
130                                 let &(outpoint_hash, outpoint_index) = outpoint;
131                                 if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {
132                                         return true;
133                                 }
134                         }
135                 }
136                 false
137         }
138 }