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