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};
8 /// An interface to request notification of certain scripts as they appear the
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
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);
17 /// Provides an outpoint which must be watched for, providing any transactions which spend the
19 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
21 /// Indicates that a listener needs to see all transactions.
22 fn watch_all_txn(&self);
24 fn register_listener(&self, listener: Weak<ChainListener>);
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);
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);
48 pub enum ConfirmationTarget {
54 /// A trait which should be implemented to provide feerate information on a number of time
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
59 pub trait FeeEstimator: Sync + Send {
60 /// Gets estimated satoshis of fee required per 1000 Weight-Units. This translates to:
61 /// * satoshis-per-byte * 250
62 /// * ceil(satoshis-per-kbyte / 4)
63 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
64 /// don't put us below 1 satoshi-per-byte).
65 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
68 /// Utility to capture some common parts of ChainWatchInterface implementors.
69 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
70 pub struct ChainWatchInterfaceUtil {
71 watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
72 listeners: Mutex<Vec<Weak<ChainListener>>>,
73 reentered: AtomicUsize
77 impl ChainWatchInterface for ChainWatchInterfaceUtil {
78 fn install_watch_script(&self, script_pub_key: &Script) {
79 let mut watched = self.watched.lock().unwrap();
80 watched.0.push(script_pub_key.clone());
81 self.reentered.fetch_add(1, Ordering::Relaxed);
84 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), _out_script: &Script) {
85 let mut watched = self.watched.lock().unwrap();
86 watched.1.push(outpoint);
87 self.reentered.fetch_add(1, Ordering::Relaxed);
90 fn watch_all_txn(&self) {
91 let mut watched = self.watched.lock().unwrap();
93 self.reentered.fetch_add(1, Ordering::Relaxed);
96 fn register_listener(&self, listener: Weak<ChainListener>) {
97 let mut vec = self.listeners.lock().unwrap();
102 impl ChainWatchInterfaceUtil {
103 pub fn new() -> ChainWatchInterfaceUtil {
104 ChainWatchInterfaceUtil {
105 watched: Mutex::new((Vec::new(), Vec::new(), false)),
106 listeners: Mutex::new(Vec::new()),
107 reentered: AtomicUsize::new(1)
111 /// Notify listeners that a block was connected given a full, unfiltered block.
112 /// Handles re-scanning the block and calling block_connected again if listeners register new
113 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
114 pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
115 let mut reentered = true;
117 let mut matched = Vec::new();
118 let mut matched_index = Vec::new();
120 let watched = self.watched.lock().unwrap();
121 for (index, transaction) in block.txdata.iter().enumerate() {
122 if self.does_match_tx_unguarded(transaction, &watched) {
123 matched.push(transaction);
124 matched_index.push(index as u32);
128 reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
132 /// Notify listeners that a block was disconnected.
133 pub fn block_disconnected(&self, header: &BlockHeader) {
134 let listeners = self.listeners.lock().unwrap().clone();
135 for listener in listeners.iter() {
136 match listener.upgrade() {
137 Some(arc) => arc.block_disconnected(header),
143 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
144 /// block which matched the filter (probably using does_match_tx).
145 /// Returns true if notified listeners registered additional watch data (implying that the
146 /// block must be re-scanned and this function called again prior to further block_connected
147 /// calls, see ChainListener::block_connected for more info).
148 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
149 let last_seen = self.reentered.load(Ordering::Relaxed);
151 let listeners = self.listeners.lock().unwrap().clone();
152 for listener in listeners.iter() {
153 match listener.upgrade() {
154 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
158 return last_seen != self.reentered.load(Ordering::Relaxed);
161 /// Checks if a given transaction matches the current filter.
162 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
163 let watched = self.watched.lock().unwrap();
164 self.does_match_tx_unguarded (tx, &watched)
167 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
171 for out in tx.output.iter() {
172 for script in watched.0.iter() {
173 if script[..] == out.script_pubkey[..] {
178 for input in tx.input.iter() {
179 for outpoint in watched.1.iter() {
180 let &(outpoint_hash, outpoint_index) = outpoint;
181 if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {