-/// Utility to capture some common parts of ChainWatchInterface implementors.
-///
-/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
-pub struct ChainWatchInterfaceUtil {
- network: Network,
- watched: Mutex<ChainWatchedUtil>,
- reentered: AtomicUsize,
-}
-
-// We only expose PartialEq in test since its somewhat unclear exactly what it should do and we're
-// only comparing a subset of fields (essentially just checking that the set of things we're
-// watching is the same).
-#[cfg(test)]
-impl PartialEq for ChainWatchInterfaceUtil {
- fn eq(&self, o: &Self) -> bool {
- self.network == o.network &&
- *self.watched.lock().unwrap() == *o.watched.lock().unwrap()
- }
-}
-
-/// Register listener
-impl ChainWatchInterface for ChainWatchInterfaceUtil {
- fn install_watch_tx(&self, txid: &Txid, script_pub_key: &Script) {
- let mut watched = self.watched.lock().unwrap();
- if watched.register_tx(txid, script_pub_key) {
- self.reentered.fetch_add(1, Ordering::Relaxed);
- }
- }
-
- fn install_watch_outpoint(&self, outpoint: (Txid, u32), out_script: &Script) {
- let mut watched = self.watched.lock().unwrap();
- if watched.register_outpoint(outpoint, out_script) {
- self.reentered.fetch_add(1, Ordering::Relaxed);
- }
- }
-
- fn watch_all_txn(&self) {
- let mut watched = self.watched.lock().unwrap();
- if watched.watch_all() {
- self.reentered.fetch_add(1, Ordering::Relaxed);
- }
- }
-
- fn get_chain_utxo(&self, genesis_hash: BlockHash, _unspent_tx_output_identifier: u64) -> Result<(Script, u64), ChainError> {
- if genesis_hash != genesis_block(self.network).header.bitcoin_hash() {
- return Err(ChainError::NotWatched);
- }
- Err(ChainError::NotSupported)
- }
-
- fn filter_block(&self, block: &Block) -> Vec<usize> {
- let mut matched_index = Vec::new();
- {
- let watched = self.watched.lock().unwrap();
- for (index, transaction) in block.txdata.iter().enumerate() {
- if self.does_match_tx_unguarded(transaction, &watched) {
- matched_index.push(index);
- }
- }
- }
- matched_index
- }
-
- fn reentered(&self) -> usize {
- self.reentered.load(Ordering::Relaxed)
- }
-}
-
-impl ChainWatchInterfaceUtil {
- /// Creates a new ChainWatchInterfaceUtil for the given network
- pub fn new(network: Network) -> ChainWatchInterfaceUtil {
- ChainWatchInterfaceUtil {
- network,
- watched: Mutex::new(ChainWatchedUtil::new()),
- reentered: AtomicUsize::new(1),
- }
- }
-
- /// Checks if a given transaction matches the current filter.
- pub fn does_match_tx(&self, tx: &Transaction) -> bool {
- let watched = self.watched.lock().unwrap();
- self.does_match_tx_unguarded (tx, &watched)
- }
-
- fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
- watched.does_match_tx(tx)
- }
-}
-