use bitcoin::blockdata::block::BlockHeader;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::script::Script;
use bitcoin::util::hash::Sha256dHash;
use std::sync::{Weak,Mutex};
pub trait ChainWatchInterface: Sync + Send {
fn install_watch_script(&self, script_pub_key: Script);
fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32));
fn watch_all_txn(&self);
fn broadcast_transaction(&self, tx: &Transaction);
fn register_listener(&self, listener: Weak<ChainListener>);
}
pub trait ChainListener: Sync + Send {
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
fn block_disconnected(&self, header: &BlockHeader);
}
pub enum ConfirmationTarget {
Background,
Normal,
HighPriority,
}
pub trait FeeEstimator: Sync + Send {
fn get_est_sat_per_vbyte(&self, ConfirmationTarget) -> u64;
}
pub struct ChainWatchInterfaceUtil {
watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, listeners: Mutex<Vec<Weak<ChainListener>>>,
}
impl ChainWatchInterfaceUtil {
pub fn new() -> ChainWatchInterfaceUtil {
ChainWatchInterfaceUtil {
watched: Mutex::new((Vec::new(), Vec::new(), false)),
listeners: Mutex::new(Vec::new()),
}
}
pub fn install_watch_script(&self, spk: Script) {
let mut watched = self.watched.lock().unwrap();
watched.0.push(Script::from(spk));
}
pub fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32)) {
let mut watched = self.watched.lock().unwrap();
watched.1.push(outpoint);
}
pub fn watch_all_txn(&self) { let mut watched = self.watched.lock().unwrap();
watched.2 = true;
}
pub fn register_listener(&self, listener: Weak<ChainListener>) {
let mut vec = self.listeners.lock().unwrap();
vec.push(listener);
}
pub fn do_call_block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
let listeners = self.listeners.lock().unwrap().clone();
for listener in listeners.iter() {
match listener.upgrade() {
Some(arc) => arc.block_connected(header, height, txn_matched, indexes_of_txn_matched),
None => ()
}
}
}
pub fn do_call_block_disconnected(&self, header: &BlockHeader) {
let listeners = self.listeners.lock().unwrap().clone();
for listener in listeners.iter() {
match listener.upgrade() {
Some(arc) => arc.block_disconnected(header),
None => ()
}
}
}
pub fn does_match_tx(&self, tx: &Transaction) -> bool {
let watched = self.watched.lock().unwrap();
if watched.2 {
return true;
}
for out in tx.output.iter() {
for script in watched.0.iter() {
if script[..] == out.script_pubkey[..] {
return true;
}
}
}
for input in tx.input.iter() {
for outpoint in watched.1.iter() {
let &(outpoint_hash, outpoint_index) = outpoint;
if outpoint_hash == input.prev_hash && outpoint_index == input.prev_index {
return true;
}
}
}
false
}
}