Skip to content

Commit e1ffd9f

Browse files
committed
Ensure transactions_confirmed is idempotent
In many complexity-reduced implementations of chain syncing using esplora `transactions_confirmed` may be called redundantly for transactions which were already confirmed. To ensure this is idempotent we add two new `ConnectionStyle`s in our tests which (a) call `transactions_confirmed` twice for each call, ensuring simple idempotency is ensured and (b) call `transactions_confirmed` once for each historical block every time we're connecting a new block, ensuring we're fully idempotent even if every call is repeated constantly. In order to actually behave correctly this requires a simple already-confirmed check in `ChannelMonitor`, which is included.
1 parent 4883eba commit e1ffd9f

File tree

3 files changed

+56
-8
lines changed

3 files changed

+56
-8
lines changed

lightning/src/chain/channelmonitor.rs

+12-1
Original file line numberDiff line numberDiff line change
@@ -2860,7 +2860,18 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
28602860

28612861
let mut watch_outputs = Vec::new();
28622862
let mut claimable_outpoints = Vec::new();
2863-
for tx in &txn_matched {
2863+
'tx_iter: for tx in &txn_matched {
2864+
for ev in self.onchain_events_awaiting_threshold_conf.iter() {
2865+
if ev.txid == tx.txid() {
2866+
// If a transaction has already been confirmed, ensure we don't bother processing it duplicatively.
2867+
if let Some(conf_hash) = ev.block_hash {
2868+
assert_eq!(header.block_hash(), conf_hash,
2869+
"Transaction {} was already confirmed and is being re-confirmed in a different block.\n\
2870+
This indicates a severe bug in the transaction connection logic - a reorg should have been processed first!", ev.txid);
2871+
}
2872+
continue 'tx_iter;
2873+
}
2874+
}
28642875
if tx.input.len() == 1 {
28652876
// Assuming our keys were not leaked (in which case we're screwed no matter what),
28662877
// commitment transactions and HTLC transactions will all only ever have one input,

lightning/src/ln/functional_test_utils.rs

+41-5
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,14 @@ pub enum ConnectStyle {
107107
/// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
108108
/// make a single `best_block_updated` call.
109109
TransactionsFirstSkippingBlocks,
110+
/// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
111+
/// make a single `best_block_updated` call. Further, we call transactions_confirmed multiple
112+
/// times to ensure its idempotent.
113+
TransactionsDuplicativelyFirstSkippingBlocks,
114+
/// The same as `TransactionsFirst`, however when we have multiple blocks to connect, we only
115+
/// make a single `best_block_updated` call. Further, we call transactions_confirmed multiple
116+
/// times to ensure its idempotent.
117+
HighlyRedundantTransactionsFirstSkippingBlocks,
110118
/// The same as `TransactionsFirst` when connecting blocks. During disconnection only
111119
/// `transaction_unconfirmed` is called.
112120
TransactionsFirstReorgsOnlyTip,
@@ -121,14 +129,16 @@ impl ConnectStyle {
121129
use core::hash::{BuildHasher, Hasher};
122130
// Get a random value using the only std API to do so - the DefaultHasher
123131
let rand_val = std::collections::hash_map::RandomState::new().build_hasher().finish();
124-
let res = match rand_val % 7 {
132+
let res = match rand_val % 9 {
125133
0 => ConnectStyle::BestBlockFirst,
126134
1 => ConnectStyle::BestBlockFirstSkippingBlocks,
127135
2 => ConnectStyle::BestBlockFirstReorgsOnlyTip,
128136
3 => ConnectStyle::TransactionsFirst,
129137
4 => ConnectStyle::TransactionsFirstSkippingBlocks,
130-
5 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
131-
6 => ConnectStyle::FullBlockViaListen,
138+
5 => ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks,
139+
6 => ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks,
140+
7 => ConnectStyle::TransactionsFirstReorgsOnlyTip,
141+
8 => ConnectStyle::FullBlockViaListen,
132142
_ => unreachable!(),
133143
};
134144
eprintln!("Using Block Connection Style: {:?}", res);
@@ -143,6 +153,7 @@ impl ConnectStyle {
143153
pub fn connect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, depth: u32) -> BlockHash {
144154
let skip_intermediaries = match *node.connect_style.borrow() {
145155
ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
156+
ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
146157
ConnectStyle::BestBlockFirstReorgsOnlyTip|ConnectStyle::TransactionsFirstReorgsOnlyTip => true,
147158
_ => false,
148159
};
@@ -193,8 +204,32 @@ fn do_connect_block<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, block: Block, sk
193204
node.node.best_block_updated(&block.header, height);
194205
node.node.transactions_confirmed(&block.header, &txdata, height);
195206
},
196-
ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|ConnectStyle::TransactionsFirstReorgsOnlyTip => {
207+
ConnectStyle::TransactionsFirst|ConnectStyle::TransactionsFirstSkippingBlocks|
208+
ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks|ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|
209+
ConnectStyle::TransactionsFirstReorgsOnlyTip => {
210+
if *node.connect_style.borrow() == ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks {
211+
let mut connections = Vec::new();
212+
for (block, height) in node.blocks.lock().unwrap().iter() {
213+
if !block.txdata.is_empty() {
214+
// Reconnect all transactions we've ever seen to ensure transaction connection
215+
// is *really* idempotent. This is a somewhat likely deployment for some
216+
// esplora implementations of chain sync which try to reduce state and
217+
// complexity as much as possible.
218+
//
219+
// Sadly we have to clone the block here to maintain lockorder. In the
220+
// future we should consider Arc'ing the blocks to avoid this.
221+
connections.push((block.clone(), *height));
222+
}
223+
}
224+
for (old_block, height) in connections {
225+
node.chain_monitor.chain_monitor.transactions_confirmed(&old_block.header,
226+
&old_block.txdata.iter().enumerate().collect::<Vec<_>>(), height);
227+
}
228+
}
197229
node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
230+
if *node.connect_style.borrow() == ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks {
231+
node.chain_monitor.chain_monitor.transactions_confirmed(&block.header, &txdata, height);
232+
}
198233
call_claimable_balances(node);
199234
node.chain_monitor.chain_monitor.best_block_updated(&block.header, height);
200235
node.node.transactions_confirmed(&block.header, &txdata, height);
@@ -226,7 +261,8 @@ pub fn disconnect_blocks<'a, 'b, 'c, 'd>(node: &'a Node<'b, 'c, 'd>, count: u32)
226261
node.chain_monitor.chain_monitor.block_disconnected(&orig.0.header, orig.1);
227262
Listen::block_disconnected(node.node, &orig.0.header, orig.1);
228263
},
229-
ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks => {
264+
ConnectStyle::BestBlockFirstSkippingBlocks|ConnectStyle::TransactionsFirstSkippingBlocks|
265+
ConnectStyle::HighlyRedundantTransactionsFirstSkippingBlocks|ConnectStyle::TransactionsDuplicativelyFirstSkippingBlocks => {
230266
if i == count - 1 {
231267
node.chain_monitor.chain_monitor.best_block_updated(&prev.0.header, prev.1);
232268
node.node.best_block_updated(&prev.0.header, prev.1);

lightning/src/ln/payment_tests.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -785,8 +785,9 @@ fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, co
785785
let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
786786
let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
787787
.get_mut(&funding_txo).unwrap().drain().collect();
788-
// If we are using chain::Confirm instead of chain::Listen, we will get the same update twice
789-
assert!(mon_updates.len() == 1 || mon_updates.len() == 2);
788+
// If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
789+
// If we're testing connection idempotency we may get substantially more.
790+
assert!(mon_updates.len() >= 1);
790791
assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
791792
assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
792793

0 commit comments

Comments
 (0)