Skip to content

Commit 6c07555

Browse files
authored
Merge pull request #159 from ariard/channel_monitor
Add registration of commitment tx's outputs from check_spend_remote_transaction
2 parents 68d0fcd + 4b9adea commit 6c07555

File tree

4 files changed

+148
-55
lines changed

4 files changed

+148
-55
lines changed

fuzz/fuzz_targets/router_target.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ struct DummyChainWatcher {
7676
}
7777

7878
impl ChainWatchInterface for DummyChainWatcher {
79-
fn install_watch_script(&self, _script_pub_key: &Script) { }
79+
fn install_watch_tx(&self, _txid: &Sha256dHash, _script_pub_key: &Script) { }
8080
fn install_watch_outpoint(&self, _outpoint: (Sha256dHash, u32), _out_script: &Script) { }
8181
fn watch_all_txn(&self) { }
8282
fn register_listener(&self, _listener: Weak<ChainListener>) { }

src/chain/chaininterface.rs

Lines changed: 112 additions & 35 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 {
@@ -25,8 +28,8 @@ pub enum ChainError {
2528
/// called from inside the library in response to ChainListener events, P2P events, or timer
2629
/// events).
2730
pub trait ChainWatchInterface: Sync + Send {
28-
/// Provides a scriptPubKey which much be watched for.
29-
fn install_watch_script(&self, script_pub_key: &Script);
31+
/// Provides a txid/random-scriptPubKey-in-the-tx which much be watched for.
32+
fn install_watch_tx(&self, txid: &Sha256dHash, script_pub_key: &Script);
3033

3134
/// Provides an outpoint which must be watched for, providing any transactions which spend the
3235
/// given outpoint.
@@ -54,9 +57,11 @@ pub trait BroadcasterInterface: Sync + Send {
5457
/// A trait indicating a desire to listen for events from the chain
5558
pub trait ChainListener: Sync + Send {
5659
/// Notifies a listener that a block was connected.
57-
/// Note that if a new script/transaction is watched during a block_connected call, the block
58-
/// *must* be re-scanned with the new script/transaction and block_connected should be called
59-
/// again with the same header and (at least) the new transactions.
60+
/// Note that if a new transaction/outpoint is watched during a block_connected call, the block
61+
/// *must* be re-scanned with the new transaction/outpoints and block_connected should be
62+
/// 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_script(&self, 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
}

src/ln/channelmanager.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3337,7 +3337,8 @@ mod tests {
33373337
nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
33383338
{
33393339
let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3340-
assert_eq!(node_txn.len(), 2);
3340+
assert_eq!(node_txn.len(), 3);
3341+
assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
33413342
assert_eq!(node_txn[0].input.len(), 1);
33423343

33433344
let mut funding_tx_map = HashMap::new();

src/ln/channelmonitor.rs

Lines changed: 33 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ pub enum ChannelMonitorUpdateErr {
4646
/// channel's monitor everywhere (including remote watchtowers) *before* this function returns. If
4747
/// an update occurs and a remote watchtower is left with old state, it may broadcast transactions
4848
/// which we have revoked, allowing our counterparty to claim all funds in the channel!
49+
/// A call to add_update_monitor is needed to register outpoint and its txid with ChainWatchInterface
50+
/// after setting funding_txo in a ChannelMonitor
4951
pub trait ManyChannelMonitor: Send + Sync {
5052
/// Adds or updates a monitor for the given `funding_txo`.
5153
fn add_update_monitor(&self, funding_txo: OutPoint, monitor: ChannelMonitor) -> Result<(), ChannelMonitorUpdateErr>;
@@ -69,7 +71,12 @@ impl<Key : Send + cmp::Eq + hash::Hash> ChainListener for SimpleManyChannelMonit
6971
fn block_connected(&self, _header: &BlockHeader, height: u32, txn_matched: &[&Transaction], _indexes_of_txn_matched: &[u32]) {
7072
let monitors = self.monitors.lock().unwrap();
7173
for monitor in monitors.values() {
72-
monitor.block_connected(txn_matched, height, &*self.broadcaster);
74+
let txn_outputs = monitor.block_connected(txn_matched, height, &*self.broadcaster);
75+
for (ref txid, ref outputs) in txn_outputs {
76+
for (idx, output) in outputs.iter().enumerate() {
77+
self.chain_monitor.install_watch_outpoint((txid.clone(), idx as u32), &output.script_pubkey);
78+
}
79+
}
7380
}
7481
}
7582

@@ -97,7 +104,7 @@ impl<Key : Send + cmp::Eq + hash::Hash + 'static> SimpleManyChannelMonitor<Key>
97104
match &monitor.funding_txo {
98105
&None => self.chain_monitor.watch_all_txn(),
99106
&Some((ref outpoint, ref script)) => {
100-
self.chain_monitor.install_watch_script(script);
107+
self.chain_monitor.install_watch_tx(&outpoint.txid, script);
101108
self.chain_monitor.install_watch_outpoint((outpoint.txid, outpoint.index as u32), script);
102109
},
103110
}
@@ -464,8 +471,9 @@ impl ChannelMonitor {
464471
/// optional, without it this monitor cannot be used in an SPV client, but you may wish to
465472
/// avoid this (or call unset_funding_info) on a monitor you wish to send to a watchtower as it
466473
/// provides slightly better privacy.
474+
/// It's the responsability of the caller to register outpoint and script with passing the former
475+
/// value as key to add_update_monitor.
467476
pub(super) fn set_funding_info(&mut self, funding_info: (OutPoint, Script)) {
468-
//TODO: Need to register the given script here with a chain_monitor
469477
self.funding_txo = Some(funding_info);
470478
}
471479

@@ -908,22 +916,24 @@ impl ChannelMonitor {
908916
/// height > height + CLTV_SHARED_CLAIM_BUFFER. In any case, will install monitoring for
909917
/// HTLC-Success/HTLC-Timeout transactions, and claim them using the revocation key (if
910918
/// applicable) as well.
911-
fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> Vec<Transaction> {
919+
fn check_spend_remote_transaction(&self, tx: &Transaction, height: u32) -> (Vec<Transaction>, (Sha256dHash, Vec<TxOut>)) {
912920
// Most secp and related errors trying to create keys means we have no hope of constructing
913921
// a spend transaction...so we return no transactions to broadcast
914922
let mut txn_to_broadcast = Vec::new();
923+
let mut watch_outputs = Vec::new();
924+
925+
let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
926+
let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
927+
915928
macro_rules! ignore_error {
916929
( $thing : expr ) => {
917930
match $thing {
918931
Ok(a) => a,
919-
Err(_) => return txn_to_broadcast
932+
Err(_) => return (txn_to_broadcast, (commitment_txid, watch_outputs))
920933
}
921934
};
922935
}
923936

924-
let commitment_txid = tx.txid(); //TODO: This is gonna be a performance bottleneck for watchtowers!
925-
let per_commitment_option = self.remote_claimable_outpoints.get(&commitment_txid);
926-
927937
let commitment_number = 0xffffffffffff - ((((tx.input[0].sequence as u64 & 0xffffff) << 3*8) | (tx.lock_time as u64 & 0xffffff)) ^ self.commitment_transaction_number_obscure_factor);
928938
if commitment_number >= self.get_min_seen_secret() {
929939
let secret = self.get_secret(commitment_number).unwrap();
@@ -942,7 +952,7 @@ impl ChannelMonitor {
942952
};
943953
let delayed_key = ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &self.delayed_payment_base_key));
944954
let a_htlc_key = match self.their_htlc_base_key {
945-
None => return txn_to_broadcast,
955+
None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
946956
Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, &PublicKey::from_secret_key(&self.secp_ctx, &per_commitment_key), &their_htlc_base_key)),
947957
};
948958

@@ -1009,7 +1019,7 @@ impl ChannelMonitor {
10091019
if htlc.transaction_output_index as usize >= tx.output.len() ||
10101020
tx.output[htlc.transaction_output_index as usize].value != htlc.amount_msat / 1000 ||
10111021
tx.output[htlc.transaction_output_index as usize].script_pubkey != expected_script.to_v0_p2wsh() {
1012-
return txn_to_broadcast; // Corrupted per_commitment_data, fuck this user
1022+
return (txn_to_broadcast, (commitment_txid, watch_outputs)); // Corrupted per_commitment_data, fuck this user
10131023
}
10141024
let input = TxIn {
10151025
previous_output: BitcoinOutPoint {
@@ -1044,10 +1054,10 @@ impl ChannelMonitor {
10441054

10451055
if !inputs.is_empty() || !txn_to_broadcast.is_empty() { // ie we're confident this is actually ours
10461056
// We're definitely a remote commitment transaction!
1047-
// TODO: Register all outputs in commitment_tx with the ChainWatchInterface!
1057+
watch_outputs.append(&mut tx.output.clone());
10481058
self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
10491059
}
1050-
if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
1060+
if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
10511061

10521062
let outputs = vec!(TxOut {
10531063
script_pubkey: self.destination_script.clone(),
@@ -1077,7 +1087,7 @@ impl ChannelMonitor {
10771087
// already processed the block, resulting in the remote_commitment_txn_on_chain entry
10781088
// not being generated by the above conditional. Thus, to be safe, we go ahead and
10791089
// insert it here.
1080-
// TODO: Register all outputs in commitment_tx with the ChainWatchInterface!
1090+
watch_outputs.append(&mut tx.output.clone());
10811091
self.remote_commitment_txn_on_chain.lock().unwrap().insert(commitment_txid, commitment_number);
10821092

10831093
if let Some(revocation_points) = self.their_cur_revocation_points {
@@ -1098,7 +1108,7 @@ impl ChannelMonitor {
10981108
},
10991109
};
11001110
let a_htlc_key = match self.their_htlc_base_key {
1101-
None => return txn_to_broadcast,
1111+
None => return (txn_to_broadcast, (commitment_txid, watch_outputs)),
11021112
Some(their_htlc_base_key) => ignore_error!(chan_utils::derive_public_key(&self.secp_ctx, revocation_point, &their_htlc_base_key)),
11031113
};
11041114

@@ -1161,7 +1171,7 @@ impl ChannelMonitor {
11611171
}
11621172
}
11631173

1164-
if inputs.is_empty() { return txn_to_broadcast; } // Nothing to be done...probably a false positive/local tx
1174+
if inputs.is_empty() { return (txn_to_broadcast, (commitment_txid, watch_outputs)); } // Nothing to be done...probably a false positive/local tx
11651175

11661176
let outputs = vec!(TxOut {
11671177
script_pubkey: self.destination_script.clone(),
@@ -1189,7 +1199,7 @@ impl ChannelMonitor {
11891199
//TODO: For each input check if its in our remote_commitment_txn_on_chain map!
11901200
}
11911201

1192-
txn_to_broadcast
1202+
(txn_to_broadcast, (commitment_txid, watch_outputs))
11931203
}
11941204

11951205
fn broadcast_by_local_state(&self, local_tx: &LocalSignedTx) -> Vec<Transaction> {
@@ -1250,11 +1260,15 @@ impl ChannelMonitor {
12501260
Vec::new()
12511261
}
12521262

1253-
fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface) {
1263+
fn block_connected(&self, txn_matched: &[&Transaction], height: u32, broadcaster: &BroadcasterInterface)-> Vec<(Sha256dHash, Vec<TxOut>)> {
1264+
let mut watch_outputs = Vec::new();
12541265
for tx in txn_matched {
12551266
for txin in tx.input.iter() {
12561267
if self.funding_txo.is_none() || (txin.previous_output.txid == self.funding_txo.as_ref().unwrap().0.txid && txin.previous_output.vout == self.funding_txo.as_ref().unwrap().0.index as u32) {
1257-
let mut txn = self.check_spend_remote_transaction(tx, height);
1268+
let (mut txn, new_outputs) = self.check_spend_remote_transaction(tx, height);
1269+
if !new_outputs.1.is_empty() {
1270+
watch_outputs.push(new_outputs);
1271+
}
12581272
if txn.is_empty() {
12591273
txn = self.check_spend_local_transaction(tx, height);
12601274
}
@@ -1281,6 +1295,7 @@ impl ChannelMonitor {
12811295
}
12821296
}
12831297
}
1298+
watch_outputs
12841299
}
12851300

12861301
pub fn would_broadcast_at_height(&self, height: u32) -> bool {

0 commit comments

Comments
 (0)