Skip to content

Commit 6fcac8b

Browse files
authored
Merge pull request #840 from jkczyz/2021-03-rescan-logic
Rescan dependent transactions in ChainMonitor
2 parents fe85696 + d8d9eaf commit 6fcac8b

File tree

5 files changed

+197
-11
lines changed

5 files changed

+197
-11
lines changed

lightning/src/chain/chainmonitor.rs

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
use bitcoin::blockdata::block::{Block, BlockHeader};
2727

2828
use chain;
29-
use chain::Filter;
29+
use chain::{Filter, WatchedOutput};
3030
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
3131
use chain::channelmonitor;
3232
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent, Persist};
@@ -82,18 +82,40 @@ where C::Target: chain::Filter,
8282
/// descendants of such transactions. It is not necessary to re-fetch the block to obtain
8383
/// updated `txdata`.
8484
pub fn block_connected(&self, header: &BlockHeader, txdata: &TransactionData, height: u32) {
85+
let mut dependent_txdata = Vec::new();
8586
let monitors = self.monitors.read().unwrap();
8687
for monitor in monitors.values() {
8788
let mut txn_outputs = monitor.block_connected(header, txdata, height, &*self.broadcaster, &*self.fee_estimator, &*self.logger);
8889

90+
// Register any new outputs with the chain source for filtering, storing any dependent
91+
// transactions from within the block that previously had not been included in txdata.
8992
if let Some(ref chain_source) = self.chain_source {
93+
let block_hash = header.block_hash();
9094
for (txid, outputs) in txn_outputs.drain(..) {
9195
for (idx, output) in outputs.iter() {
92-
chain_source.register_output(&OutPoint { txid, index: *idx as u16 }, &output.script_pubkey);
96+
// Register any new outputs with the chain source for filtering and recurse
97+
// if it indicates that there are dependent transactions within the block
98+
// that had not been previously included in txdata.
99+
let output = WatchedOutput {
100+
block_hash: Some(block_hash),
101+
outpoint: OutPoint { txid, index: *idx as u16 },
102+
script_pubkey: output.script_pubkey.clone(),
103+
};
104+
if let Some(tx) = chain_source.register_output(output) {
105+
dependent_txdata.push(tx);
106+
}
93107
}
94108
}
95109
}
96110
}
111+
112+
// Recursively call for any dependent transactions that were identified by the chain source.
113+
if !dependent_txdata.is_empty() {
114+
dependent_txdata.sort_unstable_by_key(|(index, _tx)| *index);
115+
dependent_txdata.dedup_by_key(|(index, _tx)| *index);
116+
let txdata: Vec<_> = dependent_txdata.iter().map(|(index, tx)| (*index, tx)).collect();
117+
self.block_connected(header, &txdata, height);
118+
}
97119
}
98120

99121
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
@@ -245,3 +267,56 @@ impl<ChannelSigner: Sign, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> even
245267
pending_events
246268
}
247269
}
270+
271+
#[cfg(test)]
272+
mod tests {
273+
use ::{check_added_monitors, get_local_commitment_txn};
274+
use ln::features::InitFeatures;
275+
use ln::functional_test_utils::*;
276+
use util::events::EventsProvider;
277+
use util::events::MessageSendEventsProvider;
278+
use util::test_utils::{OnRegisterOutput, TxOutReference};
279+
280+
/// Tests that in-block dependent transactions are processed by `block_connected` when not
281+
/// included in `txdata` but returned by [`chain::Filter::register_output`]. For instance,
282+
/// a (non-anchor) commitment transaction's HTLC output may be spent in the same block as the
283+
/// commitment transaction itself. An Electrum client may filter the commitment transaction but
284+
/// needs to return the HTLC transaction so it can be processed.
285+
#[test]
286+
fn connect_block_checks_dependent_transactions() {
287+
let chanmon_cfgs = create_chanmon_cfgs(2);
288+
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
289+
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
290+
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
291+
let channel = create_announced_chan_between_nodes(
292+
&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
293+
294+
// Send a payment, saving nodes[0]'s revoked commitment and HTLC-Timeout transactions.
295+
let (commitment_tx, htlc_tx) = {
296+
let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000).0;
297+
let mut txn = get_local_commitment_txn!(nodes[0], channel.2);
298+
claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 5_000_000);
299+
300+
assert_eq!(txn.len(), 2);
301+
(txn.remove(0), txn.remove(0))
302+
};
303+
304+
// Set expectations on nodes[1]'s chain source to return dependent transactions.
305+
let htlc_output = TxOutReference(commitment_tx.clone(), 0);
306+
let to_local_output = TxOutReference(commitment_tx.clone(), 1);
307+
let htlc_timeout_output = TxOutReference(htlc_tx.clone(), 0);
308+
nodes[1].chain_source
309+
.expect(OnRegisterOutput { with: htlc_output, returns: Some((1, htlc_tx)) })
310+
.expect(OnRegisterOutput { with: to_local_output, returns: None })
311+
.expect(OnRegisterOutput { with: htlc_timeout_output, returns: None });
312+
313+
// Notify nodes[1] that nodes[0]'s revoked commitment transaction was mined. The chain
314+
// source should return the dependent HTLC transaction when the HTLC output is registered.
315+
mine_transaction(&nodes[1], &commitment_tx);
316+
317+
// Clean up so uninteresting assertions don't fail.
318+
check_added_monitors!(nodes[1], 1);
319+
nodes[1].node.get_and_clear_pending_msg_events();
320+
nodes[1].node.get_and_clear_pending_events();
321+
}
322+
}

lightning/src/chain/channelmonitor.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLC
4040
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
4141
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
4242
use chain;
43+
use chain::WatchedOutput;
4344
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
4445
use chain::transaction::{OutPoint, TransactionData};
4546
use chain::keysinterface::{SpendableOutputDescriptor, StaticPaymentOutputDescriptor, DelayedPaymentOutputDescriptor, Sign, KeysInterface};
@@ -1174,7 +1175,11 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
11741175
for (txid, outputs) in lock.get_outputs_to_watch().iter() {
11751176
for (index, script_pubkey) in outputs.iter() {
11761177
assert!(*index <= u16::max_value() as u32);
1177-
filter.register_output(&OutPoint { txid: *txid, index: *index as u16 }, script_pubkey);
1178+
filter.register_output(WatchedOutput {
1179+
block_hash: None,
1180+
outpoint: OutPoint { txid: *txid, index: *index as u16 },
1181+
script_pubkey: script_pubkey.clone(),
1182+
});
11781183
}
11791184
}
11801185
}

lightning/src/chain/mod.rs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
1212
use bitcoin::blockdata::block::{Block, BlockHeader};
1313
use bitcoin::blockdata::script::Script;
14-
use bitcoin::blockdata::transaction::TxOut;
14+
use bitcoin::blockdata::transaction::{Transaction, TxOut};
1515
use bitcoin::hash_types::{BlockHash, Txid};
1616

1717
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, MonitorEvent};
@@ -129,9 +129,38 @@ pub trait Filter: Send + Sync {
129129
/// a spending condition.
130130
fn register_tx(&self, txid: &Txid, script_pubkey: &Script);
131131

132-
/// Registers interest in spends of a transaction output identified by `outpoint` having
133-
/// `script_pubkey` as the spending condition.
134-
fn register_output(&self, outpoint: &OutPoint, script_pubkey: &Script);
132+
/// Registers interest in spends of a transaction output.
133+
///
134+
/// Optionally, when `output.block_hash` is set, should return any transaction spending the
135+
/// output that is found in the corresponding block along with its index.
136+
///
137+
/// This return value is useful for Electrum clients in order to supply in-block descendant
138+
/// transactions which otherwise were not included. This is not necessary for other clients if
139+
/// such descendant transactions were already included (e.g., when a BIP 157 client provides the
140+
/// full block).
141+
fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)>;
142+
}
143+
144+
/// A transaction output watched by a [`ChannelMonitor`] for spends on-chain.
145+
///
146+
/// Used to convey to a [`Filter`] such an output with a given spending condition. Any transaction
147+
/// spending the output must be given to [`ChannelMonitor::block_connected`] either directly or via
148+
/// the return value of [`Filter::register_output`].
149+
///
150+
/// If `block_hash` is `Some`, this indicates the output was created in the corresponding block and
151+
/// may have been spent there. See [`Filter::register_output`] for details.
152+
///
153+
/// [`ChannelMonitor`]: channelmonitor::ChannelMonitor
154+
/// [`ChannelMonitor::block_connected`]: channelmonitor::ChannelMonitor::block_connected
155+
pub struct WatchedOutput {
156+
/// First block where the transaction output may have been spent.
157+
pub block_hash: Option<BlockHash>,
158+
159+
/// Outpoint identifying the transaction output.
160+
pub outpoint: OutPoint,
161+
162+
/// Spending condition of the transaction output.
163+
pub script_pubkey: Script,
135164
}
136165

137166
impl<T: Listen> Listen for std::ops::Deref<Target = T> {

lightning/src/ln/functional_test_utils.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,8 @@ macro_rules! get_feerate {
341341
}
342342
}
343343

344-
#[cfg(test)]
344+
/// Returns any local commitment transactions for the channel.
345+
#[macro_export]
345346
macro_rules! get_local_commitment_txn {
346347
($node: expr, $channel_id: expr) => {
347348
{

lightning/src/util/test_utils.rs

Lines changed: 79 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
// licenses.
99

1010
use chain;
11+
use chain::WatchedOutput;
1112
use chain::chaininterface;
1213
use chain::chaininterface::ConfirmationTarget;
1314
use chain::chainmonitor;
@@ -38,7 +39,7 @@ use std::time::Duration;
3839
use std::sync::{Mutex, Arc};
3940
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4041
use std::{cmp, mem};
41-
use std::collections::{HashMap, HashSet};
42+
use std::collections::{HashMap, HashSet, VecDeque};
4243
use chain::keysinterface::InMemorySigner;
4344

4445
pub struct TestVecWriter(pub Vec<u8>);
@@ -517,6 +518,7 @@ pub struct TestChainSource {
517518
pub utxo_ret: Mutex<Result<TxOut, chain::AccessError>>,
518519
pub watched_txn: Mutex<HashSet<(Txid, Script)>>,
519520
pub watched_outputs: Mutex<HashSet<(OutPoint, Script)>>,
521+
expectations: Mutex<Option<VecDeque<OnRegisterOutput>>>,
520522
}
521523

522524
impl TestChainSource {
@@ -527,8 +529,17 @@ impl TestChainSource {
527529
utxo_ret: Mutex::new(Ok(TxOut { value: u64::max_value(), script_pubkey })),
528530
watched_txn: Mutex::new(HashSet::new()),
529531
watched_outputs: Mutex::new(HashSet::new()),
532+
expectations: Mutex::new(None),
530533
}
531534
}
535+
536+
/// Sets an expectation that [`chain::Filter::register_output`] is called.
537+
pub fn expect(&self, expectation: OnRegisterOutput) -> &Self {
538+
self.expectations.lock().unwrap()
539+
.get_or_insert_with(|| VecDeque::new())
540+
.push_back(expectation);
541+
self
542+
}
532543
}
533544

534545
impl chain::Access for TestChainSource {
@@ -546,7 +557,72 @@ impl chain::Filter for TestChainSource {
546557
self.watched_txn.lock().unwrap().insert((*txid, script_pubkey.clone()));
547558
}
548559

549-
fn register_output(&self, outpoint: &OutPoint, script_pubkey: &Script) {
550-
self.watched_outputs.lock().unwrap().insert((*outpoint, script_pubkey.clone()));
560+
fn register_output(&self, output: WatchedOutput) -> Option<(usize, Transaction)> {
561+
let dependent_tx = match &mut *self.expectations.lock().unwrap() {
562+
None => None,
563+
Some(expectations) => match expectations.pop_front() {
564+
None => {
565+
panic!("Unexpected register_output: {:?}",
566+
(output.outpoint, output.script_pubkey));
567+
},
568+
Some(expectation) => {
569+
assert_eq!(output.outpoint, expectation.outpoint());
570+
assert_eq!(&output.script_pubkey, expectation.script_pubkey());
571+
expectation.returns
572+
},
573+
},
574+
};
575+
576+
self.watched_outputs.lock().unwrap().insert((output.outpoint, output.script_pubkey));
577+
dependent_tx
578+
}
579+
}
580+
581+
impl Drop for TestChainSource {
582+
fn drop(&mut self) {
583+
if std::thread::panicking() {
584+
return;
585+
}
586+
587+
if let Some(expectations) = &*self.expectations.lock().unwrap() {
588+
if !expectations.is_empty() {
589+
panic!("Unsatisfied expectations: {:?}", expectations);
590+
}
591+
}
592+
}
593+
}
594+
595+
/// An expectation that [`chain::Filter::register_output`] was called with a transaction output and
596+
/// returns an optional dependent transaction that spends the output in the same block.
597+
pub struct OnRegisterOutput {
598+
/// The transaction output to register.
599+
pub with: TxOutReference,
600+
601+
/// A dependent transaction spending the output along with its position in the block.
602+
pub returns: Option<(usize, Transaction)>,
603+
}
604+
605+
/// A transaction output as identified by an index into a transaction's output list.
606+
pub struct TxOutReference(pub Transaction, pub usize);
607+
608+
impl OnRegisterOutput {
609+
fn outpoint(&self) -> OutPoint {
610+
let txid = self.with.0.txid();
611+
let index = self.with.1 as u16;
612+
OutPoint { txid, index }
613+
}
614+
615+
fn script_pubkey(&self) -> &Script {
616+
let index = self.with.1;
617+
&self.with.0.output[index].script_pubkey
618+
}
619+
}
620+
621+
impl std::fmt::Debug for OnRegisterOutput {
622+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
623+
f.debug_struct("OnRegisterOutput")
624+
.field("outpoint", &self.outpoint())
625+
.field("script_pubkey", self.script_pubkey())
626+
.finish()
551627
}
552628
}

0 commit comments

Comments
 (0)