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));
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 fn get_est_sat_per_vbyte(&self, confirmation_target: ConfirmationTarget) -> u64;
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
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::from(script_pub_key));
76 self.reentered.fetch_add(1, Ordering::Relaxed);
79 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
80 let mut watched = self.watched.lock().unwrap();
81 watched.1.push(outpoint);
82 self.reentered.fetch_add(1, Ordering::Relaxed);
85 fn watch_all_txn(&self) {
86 let mut watched = self.watched.lock().unwrap();
88 self.reentered.fetch_add(1, Ordering::Relaxed);
91 fn register_listener(&self, listener: Weak<ChainListener>) {
92 let mut vec = self.listeners.lock().unwrap();
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)
106 /// Notify listeners that a block was connected.
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;
112 let mut matched = Vec::new();
113 let mut matched_index = Vec::new();
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);
123 reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
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),
138 /// Notify listeners that a block was connected.
139 /// Returns true if notified listeners registered additional watch data (implying that the
140 /// block must be re-scanned and this function called again prior to further block_connected
141 /// calls, see ChainListener::block_connected for more info).
142 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
143 let last_seen = self.reentered.load(Ordering::Relaxed);
145 let listeners = self.listeners.lock().unwrap().clone();
146 for listener in listeners.iter() {
147 match listener.upgrade() {
148 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
152 return last_seen != self.reentered.load(Ordering::Relaxed);
155 /// Checks if a given transaction matches the current filter.
156 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
157 let watched = self.watched.lock().unwrap();
158 self.does_match_tx_unguarded (tx, &watched)
161 fn does_match_tx_unguarded (&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
165 for out in tx.output.iter() {
166 for script in watched.0.iter() {
167 if script[..] == out.script_pubkey[..] {
172 for input in tx.input.iter() {
173 for outpoint in watched.1.iter() {
174 let &(outpoint_hash, outpoint_index) = outpoint;
175 if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {