1 use bitcoin::blockdata::block::{Block, BlockHeader};
2 use bitcoin::blockdata::transaction::Transaction;
3 use bitcoin::blockdata::script::Script;
4 use bitcoin::blockdata::constants::genesis_block;
5 use bitcoin::util::hash::Sha256dHash;
6 use bitcoin::network::constants::Network;
7 use bitcoin::network::serialize::BitcoinHash;
8 use util::logger::Logger;
9 use std::sync::{Mutex,Weak,MutexGuard,Arc};
10 use std::sync::atomic::{AtomicUsize, Ordering};
12 /// Used to give chain error details upstream
14 /// Chain isn't supported
16 /// Chain isn't the one watched
20 /// Tx isn't confirmed
24 /// An interface to request notification of certain scripts as they appear the
26 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
27 /// called from inside the library in response to ChainListener events, P2P events, or timer
29 pub trait ChainWatchInterface: Sync + Send {
30 /// Provides a scriptPubKey which much be watched for.
31 fn install_watch_script(&self, script_pub_key: &Script);
33 /// Provides an outpoint which must be watched for, providing any transactions which spend the
35 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script);
37 /// Indicates that a listener needs to see all transactions.
38 fn watch_all_txn(&self);
40 fn register_listener(&self, listener: Weak<ChainListener>);
43 /// Gets the chain currently watched
44 fn get_network(&self) -> Network;
46 /// Gets the script and value in satoshis for a given txid and outpoint index
47 fn get_chain_txo(&self, genesis_hash: Sha256dHash, txid: Sha256dHash, output_index: u16) -> Result<(Script, u64), ChainError>;
49 /// Gets if outpoint is among UTXO
50 fn get_spendable_outpoint(&self, genesis_hash: Sha256dHash, txid: Sha256dHash, output_index: u16) -> Result<bool, ChainError>;
53 /// An interface to send a transaction to the Bitcoin network.
54 pub trait BroadcasterInterface: Sync + Send {
55 /// Sends a transaction out to (hopefully) be mined.
56 fn broadcast_transaction(&self, tx: &Transaction);
59 /// A trait indicating a desire to listen for events from the chain
60 pub trait ChainListener: Sync + Send {
61 /// Notifies a listener that a block was connected.
62 /// Note that if a new script/transaction is watched during a block_connected call, the block
63 /// *must* be re-scanned with the new script/transaction and block_connected should be called
64 /// again with the same header and (at least) the new transactions.
65 /// This also means those counting confirmations using block_connected callbacks should watch
66 /// for duplicate headers and not count them towards confirmations!
67 fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
68 /// Notifies a listener that a block was disconnected.
69 /// Unlike block_connected, this *must* never be called twice for the same disconnect event.
70 fn block_disconnected(&self, header: &BlockHeader);
73 pub enum ConfirmationTarget {
79 /// A trait which should be implemented to provide feerate information on a number of time
81 /// Note that all of the functions implemented here *must* be reentrant-safe (obviously - they're
82 /// called from inside the library in response to ChainListener events, P2P events, or timer
84 pub trait FeeEstimator: Sync + Send {
85 /// Gets estimated satoshis of fee required per 1000 Weight-Units. This translates to:
86 /// * satoshis-per-byte * 250
87 /// * ceil(satoshis-per-kbyte / 4)
88 /// Must be no smaller than 253 (ie 1 satoshi-per-byte rounded up to ensure later round-downs
89 /// don't put us below 1 satoshi-per-byte).
90 fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
93 /// Utility to capture some common parts of ChainWatchInterface implementors.
94 /// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
95 pub struct ChainWatchInterfaceUtil {
97 watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
98 listeners: Mutex<Vec<Weak<ChainListener>>>,
99 reentered: AtomicUsize,
103 macro_rules! watched_chain {
104 ($self: ident, $hash: expr) => {
105 if $hash != genesis_block($self.get_network()).header.bitcoin_hash() {
106 return Err(ChainError::NotWatched);
111 /// Register listener
112 impl ChainWatchInterface for ChainWatchInterfaceUtil {
113 fn install_watch_script(&self, script_pub_key: &Script) {
114 let mut watched = self.watched.lock().unwrap();
115 watched.0.push(script_pub_key.clone());
116 self.reentered.fetch_add(1, Ordering::Relaxed);
119 fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), _out_script: &Script) {
120 let mut watched = self.watched.lock().unwrap();
121 watched.1.push(outpoint);
122 self.reentered.fetch_add(1, Ordering::Relaxed);
125 fn watch_all_txn(&self) {
126 let mut watched = self.watched.lock().unwrap();
128 self.reentered.fetch_add(1, Ordering::Relaxed);
131 fn register_listener(&self, listener: Weak<ChainListener>) {
132 let mut vec = self.listeners.lock().unwrap();
136 fn get_network(&self) -> Network {
141 fn get_chain_txo(&self, genesis_hash: Sha256dHash, _txid: Sha256dHash, _output_index: u16) -> Result<(Script, u64), ChainError> {
142 watched_chain!(self, genesis_hash);
144 //TODO: self.BlockchainStore.get_txo(txid, output_index)
145 Err(ChainError::UnknownTx)
148 fn get_spendable_outpoint(&self, genesis_hash: Sha256dHash, _txid: Sha256dHash, _output_index: u16) -> Result<bool, ChainError> {
149 watched_chain!(self, genesis_hash);
151 //TODO: self.BlockchainStore.is_utxo(txid, output_index)
152 Err(ChainError::UnknownTx)
156 impl ChainWatchInterfaceUtil {
157 pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
158 ChainWatchInterfaceUtil {
160 watched: Mutex::new((Vec::new(), Vec::new(), false)),
161 listeners: Mutex::new(Vec::new()),
162 reentered: AtomicUsize::new(1),
167 /// Notify listeners that a block was connected given a full, unfiltered block.
168 /// Handles re-scanning the block and calling block_connected again if listeners register new
169 /// watch data during the callbacks for you (see ChainListener::block_connected for more info).
170 pub fn block_connected_with_filtering(&self, block: &Block, height: u32) {
171 let mut reentered = true;
173 let mut matched = Vec::new();
174 let mut matched_index = Vec::new();
176 let watched = self.watched.lock().unwrap();
177 for (index, transaction) in block.txdata.iter().enumerate() {
178 if self.does_match_tx_unguarded(transaction, &watched) {
179 matched.push(transaction);
180 matched_index.push(index as u32);
184 reentered = self.block_connected_checked(&block.header, height, matched.as_slice(), matched_index.as_slice());
188 /// Notify listeners that a block was disconnected.
189 pub fn block_disconnected(&self, header: &BlockHeader) {
190 let listeners = self.listeners.lock().unwrap().clone();
191 for listener in listeners.iter() {
192 match listener.upgrade() {
193 Some(arc) => arc.block_disconnected(header),
199 /// Notify listeners that a block was connected, given pre-filtered list of transactions in the
200 /// block which matched the filter (probably using does_match_tx).
201 /// Returns true if notified listeners registered additional watch data (implying that the
202 /// block must be re-scanned and this function called again prior to further block_connected
203 /// calls, see ChainListener::block_connected for more info).
204 pub fn block_connected_checked(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) -> bool {
205 let last_seen = self.reentered.load(Ordering::Relaxed);
207 let listeners = self.listeners.lock().unwrap().clone();
208 for listener in listeners.iter() {
209 match listener.upgrade() {
210 Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
214 return last_seen != self.reentered.load(Ordering::Relaxed);
217 /// Checks if a given transaction matches the current filter.
218 pub fn does_match_tx(&self, tx: &Transaction) -> bool {
219 let watched = self.watched.lock().unwrap();
220 self.does_match_tx_unguarded (tx, &watched)
223 fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
227 for out in tx.output.iter() {
228 for script in watched.0.iter() {
229 if script[..] == out.script_pubkey[..] {
234 for input in tx.input.iter() {
235 for outpoint in watched.1.iter() {
236 let &(outpoint_hash, outpoint_index) = outpoint;
237 if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {