Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); channelmonitor: Persist force-close broadcast preference by martinsaposnic · Pull Request #3893 · lightningdevkit/rust-lightning · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 43 additions & 18 deletions lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1268,6 +1268,14 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
/// The node_id of our counterparty
counterparty_node_id: PublicKey,

/// Controls whether the monitor is allowed to automatically broadcast the latest holder commitment transaction.
///
/// This flag is set to `false` when a channel is force-closed with `should_broadcast: false`,
/// indicating that broadcasting the latest holder commitment transaction would be unsafe.
///
/// Default: `true`.
allow_automated_broadcast: bool,

/// Initial counterparty commmitment data needed to recreate the commitment tx
/// in the persistence pipeline for third-party watchtowers. This will only be present on
/// monitors created after 0.0.117.
Expand DownExpand Up@@ -1570,6 +1578,7 @@ impl<Signer: EcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signer> {
(29, self.initial_counterparty_commitment_tx, option),
(31, self.funding.channel_parameters, required),
(32, self.pending_funding, optional_vec),
(33, self.allow_automated_broadcast, required),
});

Ok(())
Expand DownExpand Up@@ -1788,6 +1797,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {

best_block,
counterparty_node_id: counterparty_node_id,
allow_automated_broadcast: true,
initial_counterparty_commitment_info: None,
initial_counterparty_commitment_tx: None,
balances_empty_height: None,
Expand DownExpand Up@@ -2144,7 +2154,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
/// may be to contact the other node operator out-of-band to coordinate other options available
/// to you.
#[rustfmt::skip]
pub fn broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
pub fn force_broadcast_latest_holder_commitment_txn_unsafe<B: Deref, F: Deref, L: Deref>(
&self, broadcaster: &B, fee_estimator: &F, logger: &L
)
where
Expand DownExpand Up@@ -3681,6 +3691,32 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
Ok(())
}

fn maybe_broadcast_latest_holder_commitment_txn<B: Deref, F: Deref, L: Deref>(
&mut self, broadcaster: &B, fee_estimator: &LowerBoundedFeeEstimator<F>,
logger: &WithChannelMonitor<L>,
) where
B::Target: BroadcasterInterface,
F::Target: FeeEstimator,
L::Target: Logger,
{
if !self.allow_automated_broadcast {
return;
}
let detected_funding_spend = self.funding_spend_confirmed.is_some()
|| self
.onchain_events_awaiting_threshold_conf
.iter()
.any(|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(
logger,
"Avoiding commitment broadcast, already detected confirmed spend onchain"
);
return;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, fee_estimator, logger);
}

#[rustfmt::skip]
fn update_monitor<B: Deref, F: Deref, L: Deref>(
&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &WithChannelMonitor<L>
Expand DownExpand Up@@ -3774,28 +3810,14 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ChannelMonitorUpdateStep::ChannelForceClosed { should_broadcast } => {
log_trace!(logger, "Updating ChannelMonitor: channel force closed, should broadcast: {}", should_broadcast);
self.lockdown_from_offchain = true;
if *should_broadcast {
// There's no need to broadcast our commitment transaction if we've seen one
// confirmed (even with 1 confirmation) as it'll be rejected as
// duplicate/conflicting.
let detected_funding_spend = self.funding_spend_confirmed.is_some() ||
self.onchain_events_awaiting_threshold_conf.iter().any(
|event| matches!(event.event, OnchainEvent::FundingSpendConfirmation { .. }));
if detected_funding_spend {
log_trace!(logger, "Avoiding commitment broadcast, already detected confirmed spend onchain");
continue;
}
self.queue_latest_holder_commitment_txn_for_broadcast(broadcaster, &bounded_fee_estimator, logger);
} else if !self.holder_tx_signed {
log_error!(logger, "WARNING: You have a potentially-unsafe holder commitment transaction available to broadcast");
log_error!(logger, " in channel monitor for channel {}!", &self.channel_id());
log_error!(logger, " Read the docs for ChannelMonitor::broadcast_latest_holder_commitment_txn to take manual action!");
} else {
self.allow_automated_broadcast = *should_broadcast;
if !*should_broadcast && self.holder_tx_signed {
// If we generated a MonitorEvent::HolderForceClosed, the ChannelManager
// will still give us a ChannelForceClosed event with !should_broadcast, but we
// shouldn't print the scary warning above.
log_info!(logger, "Channel off-chain state closed after we broadcasted our latest commitment transaction.");
}
self.maybe_broadcast_latest_holder_commitment_txn(broadcaster, &bounded_fee_estimator, logger);
},
ChannelMonitorUpdateStep::ShutdownScript { scriptpubkey } => {
log_trace!(logger, "Updating ChannelMonitor with shutdown script");
Expand DownExpand Up@@ -5682,6 +5704,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
let mut first_confirmed_funding_txo = RequiredWrapper(None);
let mut channel_parameters = None;
let mut pending_funding = None;
let mut allow_automated_broadcast = None;
read_tlv_fields!(reader, {
(1, funding_spend_confirmed, option),
(3, htlcs_resolved_on_chain, optional_vec),
Expand All@@ -5700,6 +5723,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
(29, initial_counterparty_commitment_tx, option),
(31, channel_parameters, (option: ReadableArgs, None)),
(32, pending_funding, optional_vec),
(33, allow_automated_broadcast, option),
});
if let Some(payment_preimages_with_info) = payment_preimages_with_info {
if payment_preimages_with_info.len() != payment_preimages.len() {
Expand DownExpand Up@@ -5864,6 +5888,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP

best_block,
counterparty_node_id: counterparty_node_id.unwrap(),
allow_automated_broadcast: allow_automated_broadcast.unwrap_or(true),
initial_counterparty_commitment_info,
initial_counterparty_commitment_tx,
balances_empty_height,
Expand Down
7 changes: 4 additions & 3 deletions lightning/src/ln/channelmanager.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -4467,7 +4467,7 @@ where
/// Fails if `channel_id` is unknown to the manager, or if the
/// `counterparty_node_id` isn't the counterparty of the corresponding channel.
/// You can always broadcast the latest local transaction(s) via
/// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
/// [`ChannelMonitor::force_broadcast_latest_holder_commitment_txn_unsafe`].
pub fn force_close_without_broadcasting_txn(
&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, error_message: String,
) -> Result<(), APIError> {
Expand DownExpand Up@@ -7655,7 +7655,8 @@ where
ComplFunc: FnOnce(
Option<u64>,
bool,
) -> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
)
-> (Option<MonitorUpdateCompletionAction>, Option<RAAMonitorUpdateBlockingAction>),
>(
&self, prev_hop: HTLCPreviousHopData, payment_preimage: PaymentPreimage,
payment_info: Option<PaymentClaimDetails>, completion_action: ComplFunc,
Expand DownExpand Up@@ -14144,7 +14145,7 @@ where
// LDK versions prior to 0.0.116 wrote the `pending_background_events`
// `MonitorUpdateRegeneratedOnStartup`s here, however there was never a reason to do so -
// the closing monitor updates were always effectively replayed on startup (either directly
// by calling `broadcast_latest_holder_commitment_txn` on a `ChannelMonitor` during
// by calling `force_broadcast_latest_holder_commitment_txn_unsafe` on a `ChannelMonitor` during
// deserialization or, in 0.0.115, by regenerating the monitor update itself).
0u64.write(writer)?;

Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -3151,7 +3151,7 @@ fn do_test_monitor_claims_with_random_signatures(anchors: bool, confirm_counterp
(&nodes[0], &nodes[1])
};

get_monitor!(closing_node, chan_id).broadcast_latest_holder_commitment_txn(
get_monitor!(closing_node, chan_id).force_broadcast_latest_holder_commitment_txn_unsafe(
&closing_node.tx_broadcaster, &closing_node.fee_estimator, &closing_node.logger
);

Expand Down
121 changes: 121 additions & 0 deletions lightning/src/ln/reload_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1368,3 +1368,124 @@ fn test_htlc_localremoved_persistence() {
let htlc_fail_msg_after_reload = msgs.2.unwrap().update_fail_htlcs[0].clone();
assert_eq!(htlc_fail_msg, htlc_fail_msg_after_reload);
}

#[test]
fn test_deserialize_monitor_force_closed_without_broadcasting_txn() {
let chanmon_cfgs = create_chanmon_cfgs(2);
let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
let logger;
let fee_estimator;
let persister;
let new_chain_monitor;
let deserialized_chanmgr;
let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);

let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);

// send a ChannelMonitorUpdateStep::ChannelForceClosed with { should_broadcast: false } to the monitor.
// this should persist the { should_broadcast: false } on the monitor.
nodes[0]
.node
.force_close_without_broadcasting_txn(
&channel_id,
&nodes[1].node.get_our_node_id(),
"test".to_string(),
)
.unwrap();
check_closed_event!(
nodes[0],
1,
ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
[nodes[1].node.get_our_node_id()],
100000
);

// Serialize monitor and node
let mut mon_writer = test_utils::TestVecWriter(Vec::new());
get_monitor!(nodes[0], channel_id).write(&mut mon_writer).unwrap();
let monitor_bytes = mon_writer.0;
let manager_bytes = nodes[0].node.encode();

let keys_manager = &chanmon_cfgs[0].keys_manager;
logger = test_utils::TestLogger::new();
fee_estimator = test_utils::TestFeeEstimator::new(253);
persister = test_utils::TestPersister::new();
new_chain_monitor = test_utils::TestChainMonitor::new(
Some(nodes[0].chain_source),
nodes[0].tx_broadcaster,
&logger,
&fee_estimator,
&persister,
keys_manager,
);
nodes[0].chain_monitor = &new_chain_monitor;

// Deserialize
let mut mon_read = &monitor_bytes[..];
let (_, mut monitor) = <(BlockHash, ChannelMonitor<TestChannelSigner>)>::read(
&mut mon_read,
(keys_manager, keys_manager),
)
.unwrap();
assert!(mon_read.is_empty());

let mut mgr_read = &manager_bytes[..];
let mut channel_monitors = new_hash_map();

// insert a channel monitor without its corresponding channel (it was force-closed before)
// so when the channel manager deserializes, it replays the ChannelForceClosed with { should_broadcast: true }.
channel_monitors.insert(monitor.channel_id(), &monitor);
let (_, deserialized_chanmgr_tmp) = <(
BlockHash,
ChannelManager<
&test_utils::TestChainMonitor,
&test_utils::TestBroadcaster,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestKeysInterface,
&test_utils::TestFeeEstimator,
&test_utils::TestRouter,
&test_utils::TestMessageRouter,
&test_utils::TestLogger,
>,
)>::read(
&mut mgr_read,
ChannelManagerReadArgs {
default_config: UserConfig::default(),
entropy_source: keys_manager,
node_signer: keys_manager,
signer_provider: keys_manager,
fee_estimator: &fee_estimator,
router: nodes[0].router,
message_router: &nodes[0].message_router,
chain_monitor: &new_chain_monitor,
tx_broadcaster: nodes[0].tx_broadcaster,
logger: &logger,
channel_monitors,
},
)
.unwrap();
deserialized_chanmgr = deserialized_chanmgr_tmp;
nodes[0].node = &deserialized_chanmgr;

{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert!(txs.is_empty(), "Expected no transactions to be broadcasted after deserialization, because the should_broadcast was persisted as false");
}

monitor.force_broadcast_latest_holder_commitment_txn_unsafe(
&nodes[0].tx_broadcaster,
&&fee_estimator,
&&logger,
);
{
let txs = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
assert_eq!(txs.len(), 1, "Expected one transaction to be broadcasted after force_broadcast_latest_holder_commitment_txn_unsafe");
check_spends!(txs[0], funding_tx);
assert_eq!(txs[0].input[0].previous_output.txid, funding_tx.compute_txid());
}

assert!(nodes[0].chain_monitor.watch_channel(monitor.channel_id(), monitor).is_ok());
check_added_monitors!(nodes[0], 1);
}