Skip to content

Commit 47ad3d6

Browse files
committed
Handle 1-conf funding_locked in channel no matter the event order
See comment in the diff for more details
1 parent 5cd1857 commit 47ad3d6

File tree

5 files changed

+100
-60
lines changed

5 files changed

+100
-60
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -436,11 +436,10 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
436436
let mut header = BlockHeader { version: 0x20000000, prev_blockhash: chain_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
437437
let txdata: Vec<_> = channel_txn.iter().enumerate().map(|(i, tx)| (i + 1, tx)).collect();
438438
$node.transactions_confirmed(&header, 1, &txdata);
439-
$node.update_best_block(&header, 1);
440-
for i in 2..100 {
439+
for _ in 2..100 {
441440
header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
442-
$node.update_best_block(&header, i);
443441
}
442+
$node.update_best_block(&header, 99);
444443
} }
445444
}
446445

lightning/src/ln/channel.rs

Lines changed: 73 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3501,11 +3501,57 @@ impl<Signer: Sign> Channel<Signer> {
35013501
self.network_sync == UpdateStatus::DisabledMarked
35023502
}
35033503

3504+
fn check_get_funding_locked(&mut self, height: u32) -> Option<msgs::FundingLocked> {
3505+
if self.funding_tx_confirmation_height == 0 {
3506+
return None;
3507+
}
3508+
3509+
let funding_tx_confirmations = height as i64 - self.funding_tx_confirmation_height as i64 + 1;
3510+
if funding_tx_confirmations <= 0 {
3511+
self.funding_tx_confirmation_height = 0;
3512+
}
3513+
3514+
if funding_tx_confirmations < self.minimum_depth as i64 {
3515+
return None;
3516+
}
3517+
3518+
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
3519+
let need_commitment_update = if non_shutdown_state == ChannelState::FundingSent as u32 {
3520+
self.channel_state |= ChannelState::OurFundingLocked as u32;
3521+
true
3522+
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32) {
3523+
self.channel_state = ChannelState::ChannelFunded as u32 | (self.channel_state & MULTI_STATE_FLAGS);
3524+
self.update_time_counter += 1;
3525+
true
3526+
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) {
3527+
// We got a reorg but not enough to trigger a force close, just ignore.
3528+
false
3529+
} else if self.channel_state < ChannelState::ChannelFunded as u32 {
3530+
panic!("Started confirming a channel in a state pre-FundingSent?: {}", self.channel_state);
3531+
} else {
3532+
// We got a reorg but not enough to trigger a force close, just ignore.
3533+
false
3534+
};
3535+
3536+
if need_commitment_update {
3537+
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
3538+
let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
3539+
return Some(msgs::FundingLocked {
3540+
channel_id: self.channel_id,
3541+
next_per_commitment_point,
3542+
});
3543+
} else {
3544+
self.monitor_pending_funding_locked = true;
3545+
}
3546+
}
3547+
None
3548+
}
3549+
35043550
/// When a transaction is confirmed, we check whether it is or spends the funding transaction
35053551
/// In the first case, we store the confirmation height and calculating the short channel id.
35063552
/// In the second, we simply return an Err indicating we need to be force-closed now.
35073553
pub fn transactions_confirmed<L: Deref>(&mut self, block_hash: &BlockHash, height: u32, txdata: &TransactionData, logger: &L)
3508-
-> Result<(), msgs::ErrorMessage> where L::Target: Logger {
3554+
-> Result<Option<msgs::FundingLocked>, msgs::ErrorMessage> where L::Target: Logger {
35093555
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
35103556
for &(index_in_block, tx) in txdata.iter() {
35113557
if let Some(funding_txo) = self.get_funding_txo() {
@@ -3550,6 +3596,12 @@ impl<Signer: Sign> Channel<Signer> {
35503596
}
35513597
}
35523598
}
3599+
// If we allow 1-conf funding, we may need to check for funding_locked here and
3600+
// send it immediately instead of waiting for an update_best_block call (which
3601+
// may have already happened for this block).
3602+
if let Some(funding_locked) = self.check_get_funding_locked(height) {
3603+
return Ok(Some(funding_locked));
3604+
}
35533605
}
35543606
for inp in tx.input.iter() {
35553607
if inp.previous_output == funding_txo.into_bitcoin_outpoint() {
@@ -3562,7 +3614,7 @@ impl<Signer: Sign> Channel<Signer> {
35623614
}
35633615
}
35643616
}
3565-
Ok(())
3617+
Ok(None)
35663618
}
35673619

35683620
/// When a new block is connected, we check the height of the block against outbound holding
@@ -3592,59 +3644,32 @@ impl<Signer: Sign> Channel<Signer> {
35923644
});
35933645

35943646
self.update_time_counter = cmp::max(self.update_time_counter, highest_header_time);
3595-
if self.funding_tx_confirmation_height > 0 {
3596-
let funding_tx_confirmations = height as i64 - self.funding_tx_confirmation_height as i64 + 1;
3597-
if funding_tx_confirmations <= 0 {
3598-
self.funding_tx_confirmation_height = 0;
3647+
3648+
if let Some(funding_locked) = self.check_get_funding_locked(height) {
3649+
return Ok((Some(funding_locked), timed_out_htlcs));
3650+
}
3651+
3652+
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
3653+
if non_shutdown_state >= ChannelState::ChannelFunded as u32 ||
3654+
(non_shutdown_state & ChannelState::OurFundingLocked as u32) == ChannelState::OurFundingLocked as u32 {
3655+
let mut funding_tx_confirmations = height as i64 - self.funding_tx_confirmation_height as i64 + 1;
3656+
if self.funding_tx_confirmation_height == 0 {
3657+
// Note that check_get_funding_locked may reset funding_tx_confirmation_height to
3658+
// zero if it has been reorged out, however in either case, our state flags
3659+
// indicate we've already sent a funding_locked
3660+
funding_tx_confirmations = 0;
35993661
}
36003662

3601-
let non_shutdown_state = self.channel_state & (!MULTI_STATE_FLAGS);
3602-
if (non_shutdown_state >= ChannelState::ChannelFunded as u32 ||
3603-
(non_shutdown_state & ChannelState::OurFundingLocked as u32) == ChannelState::OurFundingLocked as u32) &&
3604-
funding_tx_confirmations < self.minimum_depth as i64 / 2 {
3663+
// If we've sent funding_locked (or have both sent and received funding_locked), and
3664+
// the funding transaction's confirmation count has dipped below minimum_depth / 2,
3665+
// close the channel and hope we can get the latest state on chain (because presumably
3666+
// the funding transaction is at least still in the mempool of most nodes).
3667+
if funding_tx_confirmations < self.minimum_depth as i64 / 2 {
36053668
return Err(msgs::ErrorMessage {
36063669
channel_id: self.channel_id(),
36073670
data: format!("Funding transaction was un-confirmed. Locked at {} confs, now have {} confs.", self.minimum_depth, funding_tx_confirmations),
36083671
});
36093672
}
3610-
3611-
if funding_tx_confirmations == self.minimum_depth as i64 {
3612-
let need_commitment_update = if non_shutdown_state == ChannelState::FundingSent as u32 {
3613-
self.channel_state |= ChannelState::OurFundingLocked as u32;
3614-
true
3615-
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::TheirFundingLocked as u32) {
3616-
self.channel_state = ChannelState::ChannelFunded as u32 | (self.channel_state & MULTI_STATE_FLAGS);
3617-
self.update_time_counter += 1;
3618-
true
3619-
} else if non_shutdown_state == (ChannelState::FundingSent as u32 | ChannelState::OurFundingLocked as u32) {
3620-
// We got a reorg but not enough to trigger a force close, just update
3621-
// funding_tx_confirmed_in and return.
3622-
false
3623-
} else if self.channel_state < ChannelState::ChannelFunded as u32 {
3624-
panic!("Started confirming a channel in a state pre-FundingSent?: {}", self.channel_state);
3625-
} else {
3626-
// We got a reorg but not enough to trigger a force close, just update
3627-
// funding_tx_confirmed_in and return.
3628-
false
3629-
};
3630-
3631-
//TODO: Note that this must be a duplicate of the previous commitment point they sent us,
3632-
//as otherwise we will have a commitment transaction that they can't revoke (well, kinda,
3633-
//they can by sending two revoke_and_acks back-to-back, but not really). This appears to be
3634-
//a protocol oversight, but I assume I'm just missing something.
3635-
if need_commitment_update {
3636-
if self.channel_state & (ChannelState::MonitorUpdateFailed as u32) == 0 {
3637-
let next_per_commitment_point = self.holder_signer.get_per_commitment_point(self.cur_holder_commitment_transaction_number, &self.secp_ctx);
3638-
return Ok((Some(msgs::FundingLocked {
3639-
channel_id: self.channel_id,
3640-
next_per_commitment_point,
3641-
}), timed_out_htlcs));
3642-
} else {
3643-
self.monitor_pending_funding_locked = true;
3644-
return Ok((None, timed_out_htlcs));
3645-
}
3646-
}
3647-
}
36483673
}
36493674

36503675
Ok((None, timed_out_htlcs))

lightning/src/ln/channelmanager.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3436,7 +3436,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
34363436
log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
34373437

34383438
let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3439-
self.do_chain_event(height, |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|_| (None, Vec::new())));
3439+
self.do_chain_event(height, |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|a| (a, Vec::new())));
34403440
}
34413441

34423442
/// Updates channel state with the current best blockchain tip. You should attempt to call this

lightning/src/ln/functional_tests.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,7 @@ fn test_multi_flight_update_fee() {
394394
check_added_monitors!(nodes[1], 1);
395395
}
396396

397-
#[test]
398-
fn test_1_conf_open() {
397+
fn do_test_1_conf_open(connect_style: ConnectStyle) {
399398
// Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400399
// tests that we properly send one in that case.
401400
let mut alice_config = UserConfig::default();
@@ -409,7 +408,8 @@ fn test_1_conf_open() {
409408
let chanmon_cfgs = create_chanmon_cfgs(2);
410409
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411410
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412-
let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
411+
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
412+
*nodes[0].connect_style.borrow_mut() = connect_style;
413413

414414
let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415415
mine_transaction(&nodes[1], &tx);
@@ -425,6 +425,12 @@ fn test_1_conf_open() {
425425
node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
426426
}
427427
}
428+
#[test]
429+
fn test_1_conf_open() {
430+
do_test_1_conf_open(ConnectStyle::BestBlockFirst);
431+
do_test_1_conf_open(ConnectStyle::TransactionsFirst);
432+
do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
433+
}
428434

429435
fn do_test_sanity_on_in_flight_opens(steps: u8) {
430436
// Previously, we had issues deserializing channels when we hadn't connected the first block

lightning/src/ln/reorg_tests.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ fn test_onchain_htlc_timeout_delay_remote_commitment() {
184184
do_test_onchain_htlc_reorg(false, false);
185185
}
186186

187-
fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool) {
187+
fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool, connect_style: ConnectStyle) {
188188
// After creating a chan between nodes, we disconnect all blocks previously seen to force a
189189
// channel close on nodes[0] side. We also use this to provide very basic testing of logic
190190
// around freeing background events which store monitor updates during block_[dis]connected.
@@ -195,6 +195,8 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool) {
195195
let new_chain_monitor: test_utils::TestChainMonitor;
196196
let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
197197
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
198+
*nodes[0].connect_style.borrow_mut() = connect_style;
199+
198200
let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
199201

200202
let channel_state = nodes[0].node.channel_state.lock().unwrap();
@@ -272,10 +274,18 @@ fn do_test_unconf_chan(reload_node: bool, reorg_after_reload: bool) {
272274

273275
#[test]
274276
fn test_unconf_chan() {
275-
do_test_unconf_chan(true, true);
276-
do_test_unconf_chan(false, true);
277-
do_test_unconf_chan(true, false);
278-
do_test_unconf_chan(false, false);
277+
do_test_unconf_chan(true, true, ConnectStyle::BestBlockFirstSkippingBlocks);
278+
do_test_unconf_chan(false, true, ConnectStyle::BestBlockFirstSkippingBlocks);
279+
do_test_unconf_chan(true, false, ConnectStyle::BestBlockFirstSkippingBlocks);
280+
do_test_unconf_chan(false, false, ConnectStyle::BestBlockFirstSkippingBlocks);
281+
}
282+
283+
#[test]
284+
fn test_unconf_chan_via_listen() {
285+
do_test_unconf_chan(true, true, ConnectStyle::FullBlockViaListen);
286+
do_test_unconf_chan(false, true, ConnectStyle::FullBlockViaListen);
287+
do_test_unconf_chan(true, false, ConnectStyle::FullBlockViaListen);
288+
do_test_unconf_chan(false, false, ConnectStyle::FullBlockViaListen);
279289
}
280290

281291
#[test]

0 commit comments

Comments
 (0)