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