Skip to content

Commit bfb9b46

Browse files
TheBlueMattAntoine Riard
authored andcommitted
Refactor/dont re-enter block_conencted on duplicate watch calls
Previously we'd hit an infinite loop if a block_connected call always resulted in the same ChainWatchInterface registrations. While we're at it, we also split ChainWatchUtil in two to make things a bit more flexible for users, though not sure if that actually matters, and make the matching more aggressive in testing, even if we pick the more performant option at runtime.
1 parent 90b545f commit bfb9b46

File tree

1 file changed

+107
-30
lines changed

1 file changed

+107
-30
lines changed

src/chain/chaininterface.rs

Lines changed: 107 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@ use bitcoin::blockdata::constants::genesis_block;
55
use bitcoin::util::hash::Sha256dHash;
66
use bitcoin::network::constants::Network;
77
use bitcoin::network::serialize::BitcoinHash;
8+
89
use util::logger::Logger;
10+
911
use std::sync::{Mutex,Weak,MutexGuard,Arc};
1012
use std::sync::atomic::{AtomicUsize, Ordering};
13+
use std::collections::HashSet;
1114

1215
/// Used to give chain error details upstream
1316
pub enum ChainError {
@@ -57,6 +60,8 @@ pub trait ChainListener: Sync + Send {
5760
/// Note that if a new transaction/outpoint is watched during a block_connected call, the block
5861
/// *must* be re-scanned with the new transaction/outpoints and block_connected should be
5962
/// called again with the same header and (at least) the new transactions.
63+
/// Note that if non-new transaction/outpoints may be registered during a call, a second call
64+
/// *must not* happen.
6065
/// This also means those counting confirmations using block_connected callbacks should watch
6166
/// for duplicate headers and not count them towards confirmations!
6267
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]);
@@ -85,34 +90,124 @@ pub trait FeeEstimator: Sync + Send {
8590
fn get_est_sat_per_1000_weight(&self, confirmation_target: ConfirmationTarget) -> u64;
8691
}
8792

93+
/// Utility for tracking registered txn/outpoints and checking for matches
94+
pub struct ChainWatchedUtil {
95+
watch_all: bool,
96+
97+
// We are more conservative in matching during testing to ensure everything matches *exactly*,
98+
// even though during normal runtime we take more optimized match approaches...
99+
#[cfg(test)]
100+
watched_txn: HashSet<(Sha256dHash, Script)>,
101+
#[cfg(not(test))]
102+
watched_txn: HashSet<Script>,
103+
104+
watched_outpoints: HashSet<(Sha256dHash, u32)>,
105+
}
106+
107+
impl ChainWatchedUtil {
108+
/// Constructs an empty (watches nothing) ChainWatchedUtil
109+
pub fn new() -> Self {
110+
Self {
111+
watch_all: false,
112+
watched_txn: HashSet::new(),
113+
watched_outpoints: HashSet::new(),
114+
}
115+
}
116+
117+
/// Registers a tx for monitoring, returning true if it was a new tx and false if we'd already
118+
/// been watching for it.
119+
pub fn register_tx(&mut self, txid: &Sha256dHash, script_pub_key: &Script) -> bool {
120+
if self.watch_all { return false; }
121+
#[cfg(test)]
122+
{
123+
self.watched_txn.insert((txid.clone(), script_pub_key.clone()))
124+
}
125+
#[cfg(not(test))]
126+
{
127+
let _tx_unused = txid; // Its used in cfg(test), though
128+
self.watched_txn.insert(script_pub_key.clone())
129+
}
130+
}
131+
132+
/// Registers an outpoint for monitoring, returning true if it was a new outpoint and false if
133+
/// we'd already been watching for it
134+
pub fn register_outpoint(&mut self, outpoint: (Sha256dHash, u32), _script_pub_key: &Script) -> bool {
135+
if self.watch_all { return false; }
136+
self.watched_outpoints.insert(outpoint)
137+
}
138+
139+
/// Sets us to match all transactions, returning true if this is a new setting anf false if
140+
/// we'd already been set to match everything.
141+
pub fn watch_all(&mut self) -> bool {
142+
if self.watch_all { return false; }
143+
self.watch_all = true;
144+
true
145+
}
146+
147+
/// Checks if a given transaction matches the current filter.
148+
pub fn does_match_tx(&self, tx: &Transaction) -> bool {
149+
if self.watch_all {
150+
return true;
151+
}
152+
for out in tx.output.iter() {
153+
#[cfg(test)]
154+
for &(ref txid, ref script) in self.watched_txn.iter() {
155+
if *script == out.script_pubkey {
156+
if tx.txid() == *txid {
157+
return true;
158+
}
159+
}
160+
}
161+
#[cfg(not(test))]
162+
for script in self.watched_txn.iter() {
163+
if *script == out.script_pubkey {
164+
return true;
165+
}
166+
}
167+
}
168+
for input in tx.input.iter() {
169+
for outpoint in self.watched_outpoints.iter() {
170+
let &(outpoint_hash, outpoint_index) = outpoint;
171+
if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
172+
return true;
173+
}
174+
}
175+
}
176+
false
177+
}
178+
}
179+
88180
/// Utility to capture some common parts of ChainWatchInterface implementors.
89181
/// Keeping a local copy of this in a ChainWatchInterface implementor is likely useful.
90182
pub struct ChainWatchInterfaceUtil {
91183
network: Network,
92-
watched: Mutex<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>, //TODO: Something clever to optimize this
184+
watched: Mutex<ChainWatchedUtil>,
93185
listeners: Mutex<Vec<Weak<ChainListener>>>,
94186
reentered: AtomicUsize,
95187
logger: Arc<Logger>,
96188
}
97189

98190
/// Register listener
99191
impl ChainWatchInterface for ChainWatchInterfaceUtil {
100-
fn install_watch_tx(&self, _txid: &Sha256dHash, script_pub_key: &Script) {
192+
fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script) {
101193
let mut watched = self.watched.lock().unwrap();
102-
watched.0.push(script_pub_key.clone());
103-
self.reentered.fetch_add(1, Ordering::Relaxed);
194+
if watched.register_tx(txid, script_pub_key) {
195+
self.reentered.fetch_add(1, Ordering::Relaxed);
196+
}
104197
}
105198

106-
fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), _out_script: &Script) {
199+
fn install_watch_outpoint(&self, outpoint: (Sha256dHash, u32), out_script: &Script) {
107200
let mut watched = self.watched.lock().unwrap();
108-
watched.1.push(outpoint);
109-
self.reentered.fetch_add(1, Ordering::Relaxed);
201+
if watched.register_outpoint(outpoint, out_script) {
202+
self.reentered.fetch_add(1, Ordering::Relaxed);
203+
}
110204
}
111205

112206
fn watch_all_txn(&self) {
113207
let mut watched = self.watched.lock().unwrap();
114-
watched.2 = true;
115-
self.reentered.fetch_add(1, Ordering::Relaxed);
208+
if watched.watch_all() {
209+
self.reentered.fetch_add(1, Ordering::Relaxed);
210+
}
116211
}
117212

118213
fn register_listener(&self, listener: Weak<ChainListener>) {
@@ -132,7 +227,7 @@ impl ChainWatchInterfaceUtil {
132227
pub fn new(network: Network, logger: Arc<Logger>) -> ChainWatchInterfaceUtil {
133228
ChainWatchInterfaceUtil {
134229
network: network,
135-
watched: Mutex::new((Vec::new(), Vec::new(), false)),
230+
watched: Mutex::new(ChainWatchedUtil::new()),
136231
listeners: Mutex::new(Vec::new()),
137232
reentered: AtomicUsize::new(1),
138233
logger: logger,
@@ -195,25 +290,7 @@ impl ChainWatchInterfaceUtil {
195290
self.does_match_tx_unguarded (tx, &watched)
196291
}
197292

198-
fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<(Vec<Script>, Vec<(Sha256dHash, u32)>, bool)>) -> bool {
199-
if watched.2 {
200-
return true;
201-
}
202-
for out in tx.output.iter() {
203-
for script in watched.0.iter() {
204-
if script[..] == out.script_pubkey[..] {
205-
return true;
206-
}
207-
}
208-
}
209-
for input in tx.input.iter() {
210-
for outpoint in watched.1.iter() {
211-
let &(outpoint_hash, outpoint_index) = outpoint;
212-
if outpoint_hash == input.previous_output.txid && outpoint_index == input.previous_output.vout {
213-
return true;
214-
}
215-
}
216-
}
217-
false
293+
fn does_match_tx_unguarded(&self, tx: &Transaction, watched: &MutexGuard<ChainWatchedUtil>) -> bool {
294+
watched.does_match_tx(tx)
218295
}
219296
}

0 commit comments

Comments
 (0)