Skip to content

Commit c7c8a12

Browse files
committed
Add pending-HTLC-failure to and unify force_shutdown() handling
This patch got a bit bigger than I'd intended, but primarily this unifies force_shutdown() handling so all the callsites at least look similar. It also fails backwards any HTLCs which were completely pending (ie hadn't been committed to) and ensures we broadcast our local commitment transaction. It also adds a force_close_channel method to ChannelManager to expose force-closure.
1 parent 5c32e3c commit c7c8a12

File tree

2 files changed

+129
-28
lines changed

2 files changed

+129
-28
lines changed

src/ln/channel.rs

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1836,6 +1836,7 @@ impl Channel {
18361836

18371837
/// Guaranteed to be Some after both FundingLocked messages have been exchanged (and, thus,
18381838
/// is_usable() returns true).
1839+
/// Allowed in any state (including after shutdown)
18391840
pub fn get_short_channel_id(&self) -> Option<u64> {
18401841
self.short_channel_id
18411842
}
@@ -1846,10 +1847,12 @@ impl Channel {
18461847
self.channel_monitor.get_funding_txo()
18471848
}
18481849

1850+
/// Allowed in any state (including after shutdown)
18491851
pub fn get_their_node_id(&self) -> PublicKey {
18501852
self.their_node_id
18511853
}
18521854

1855+
/// Allowed in any state (including after shutdown)
18531856
pub fn get_our_htlc_minimum_msat(&self) -> u64 {
18541857
self.our_htlc_minimum_msat
18551858
}
@@ -1858,6 +1861,7 @@ impl Channel {
18581861
self.channel_value_satoshis
18591862
}
18601863

1864+
/// Allowed in any state (including after shutdown)
18611865
pub fn get_channel_update_count(&self) -> u32 {
18621866
self.channel_update_count
18631867
}
@@ -1867,6 +1871,7 @@ impl Channel {
18671871
}
18681872

18691873
/// Gets the fee we'd want to charge for adding an HTLC output to this Channel
1874+
/// Allowed in any state (including after shutdown)
18701875
pub fn get_our_fee_base_msat(&self, fee_estimator: &FeeEstimator) -> u32 {
18711876
// For lack of a better metric, we calculate what it would cost to consolidate the new HTLC
18721877
// output value back into a transaction with the regular channel output:
@@ -1886,13 +1891,15 @@ impl Channel {
18861891
}
18871892

18881893
/// Returns true if this channel is fully established and not known to be closing.
1894+
/// Allowed in any state (including after shutdown)
18891895
pub fn is_usable(&self) -> bool {
18901896
let mask = ChannelState::ChannelFunded as u32 | BOTH_SIDES_SHUTDOWN_MASK;
18911897
(self.channel_state & mask) == (ChannelState::ChannelFunded as u32)
18921898
}
18931899

18941900
/// Returns true if this channel is currently available for use. This is a superset of
18951901
/// is_usable() and considers things like the channel being temporarily disabled.
1902+
/// Allowed in any state (including after shutdown)
18961903
pub fn is_live(&self) -> bool {
18971904
self.is_usable()
18981905
}
@@ -2332,14 +2339,39 @@ impl Channel {
23322339
}
23332340

23342341
/// Gets the latest commitment transaction and any dependant transactions for relay (forcing
2335-
/// shutdown of this channel - no more calls into this Channel may be made afterwards.
2336-
pub fn force_shutdown(&mut self) -> Vec<Transaction> {
2342+
/// shutdown of this channel - no more calls into this Channel may be made afterwards except
2343+
/// those explicitly stated to be allowed after shutdown completes, eg some simple getters).
2344+
/// Also returns the list of payment_hashes for channels which we can safely fail backwards
2345+
/// immediately (others we will have to allow to time out).
2346+
pub fn force_shutdown(&mut self) -> (Vec<Transaction>, Vec<[u8; 32]>) {
23372347
assert!(self.channel_state != ChannelState::ShutdownComplete as u32);
2348+
2349+
// We go ahead and "free" any holding cell HTLCs or HTLCs we haven't yet committed to and
2350+
// return them to fail the payment.
2351+
let mut dropped_outbound_htlcs = Vec::with_capacity(self.holding_cell_htlc_updates.len());
2352+
for htlc_update in self.holding_cell_htlc_updates.drain(..) {
2353+
match htlc_update {
2354+
HTLCUpdateAwaitingACK::AddHTLC { payment_hash, .. } => {
2355+
dropped_outbound_htlcs.push(payment_hash);
2356+
},
2357+
_ => {}
2358+
}
2359+
}
2360+
2361+
for htlc in self.pending_htlcs.drain(..) {
2362+
if htlc.state == HTLCState::LocalAnnounced {
2363+
dropped_outbound_htlcs.push(htlc.payment_hash);
2364+
}
2365+
//TODO: Do something with the remaining HTLCs
2366+
//(we need to have the ChannelManager monitor them so we can claim the inbound HTLCs
2367+
//which correspond)
2368+
}
2369+
23382370
self.channel_state = ChannelState::ShutdownComplete as u32;
23392371
self.channel_update_count += 1;
23402372
let mut res = Vec::new();
23412373
mem::swap(&mut res, &mut self.last_local_commitment_txn);
2342-
res
2374+
(res, dropped_outbound_htlcs)
23432375
}
23442376
}
23452377

src/ln/channelmanager.rs

Lines changed: 94 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,47 @@ impl ChannelManager {
365365
Ok(())
366366
}
367367

368+
#[inline]
369+
fn finish_force_close_channel(&self, shutdown_res: (Vec<Transaction>, Vec<[u8; 32]>)) {
370+
let (local_txn, failed_htlcs) = shutdown_res;
371+
for payment_hash in failed_htlcs {
372+
// unknown_next_peer...I dunno who that is anymore....
373+
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), &payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 10, data: Vec::new() });
374+
}
375+
for tx in local_txn {
376+
self.tx_broadcaster.broadcast_transaction(&tx);
377+
}
378+
//TODO: We need to have a way where outbound HTLC claims can result in us claiming the
379+
//now-on-chain HTLC output for ourselves (and, thereafter, passing the HTLC backwards).
380+
//TODO: We need to handle monitoring of pending offered HTLCs which just hit the chain and
381+
//may be claimed, resulting in us claiming the inbound HTLCs (and back-failing after
382+
//timeouts are hit and our claims confirm).
383+
}
384+
385+
/// Force closes a channel, immediately broadcasting the latest local commitment transaction to
386+
/// the chain and rejecting new HTLCs on the given channel.
387+
pub fn force_close_channel(&self, channel_id: &[u8; 32]) {
388+
let mut chan = {
389+
let mut channel_state_lock = self.channel_state.lock().unwrap();
390+
let channel_state = channel_state_lock.borrow_parts();
391+
if let Some(mut chan) = channel_state.by_id.remove(channel_id) {
392+
if let Some(short_id) = chan.get_short_channel_id() {
393+
channel_state.short_to_id.remove(&short_id);
394+
}
395+
chan
396+
} else {
397+
return;
398+
}
399+
};
400+
self.finish_force_close_channel(chan.force_shutdown());
401+
let mut events = self.pending_events.lock().unwrap();
402+
if let Ok(update) = self.get_channel_update(&chan) {
403+
events.push(events::Event::BroadcastChannelUpdate {
404+
msg: update
405+
});
406+
}
407+
}
408+
368409
#[inline]
369410
fn gen_rho_mu_from_shared_secret(shared_secret: &SharedSecret) -> ([u8; 32], [u8; 32]) {
370411
({
@@ -1092,6 +1133,7 @@ impl events::EventsProvider for ChannelManager {
10921133
impl ChainListener for ChannelManager {
10931134
fn block_connected(&self, header: &BlockHeader, height: u32, txn_matched: &[&Transaction], indexes_of_txn_matched: &[u32]) {
10941135
let mut new_events = Vec::new();
1136+
let mut failed_channels = Vec::new();
10951137
{
10961138
let mut channel_state = self.channel_state.lock().unwrap();
10971139
let mut short_to_ids_to_insert = Vec::new();
@@ -1119,7 +1161,10 @@ impl ChainListener for ChannelManager {
11191161
if let Some(short_id) = channel.get_short_channel_id() {
11201162
short_to_ids_to_remove.push(short_id);
11211163
}
1122-
channel.force_shutdown();
1164+
// It looks like our counterparty went on-chain. We go ahead and
1165+
// broadcast our latest local state as well here, just in case its
1166+
// some kind of SPV attack, though we expect these to be dropped.
1167+
failed_channels.push(channel.force_shutdown());
11231168
if let Ok(update) = self.get_channel_update(&channel) {
11241169
new_events.push(events::Event::BroadcastChannelUpdate {
11251170
msg: update
@@ -1134,7 +1179,11 @@ impl ChainListener for ChannelManager {
11341179
if let Some(short_id) = channel.get_short_channel_id() {
11351180
short_to_ids_to_remove.push(short_id);
11361181
}
1137-
channel.force_shutdown();
1182+
failed_channels.push(channel.force_shutdown());
1183+
// If would_broadcast_at_height() is true, the channel_monitor will broadcast
1184+
// the latest local tx for us, so we should skip that here (it doesn't really
1185+
// hurt anything, but does make tests a bit simpler).
1186+
failed_channels.last_mut().unwrap().0 = Vec::new();
11381187
if let Ok(update) = self.get_channel_update(&channel) {
11391188
new_events.push(events::Event::BroadcastChannelUpdate {
11401189
msg: update
@@ -1151,6 +1200,9 @@ impl ChainListener for ChannelManager {
11511200
channel_state.short_to_id.insert(to_insert.0, to_insert.1);
11521201
}
11531202
}
1203+
for failure in failed_channels.drain(..) {
1204+
self.finish_force_close_channel(failure);
1205+
}
11541206
let mut pending_events = self.pending_events.lock().unwrap();
11551207
for funding_locked in new_events.drain(..) {
11561208
pending_events.push(funding_locked);
@@ -1160,23 +1212,38 @@ impl ChainListener for ChannelManager {
11601212

11611213
/// We force-close the channel without letting our counterparty participate in the shutdown
11621214
fn block_disconnected(&self, header: &BlockHeader) {
1163-
let mut channel_lock = self.channel_state.lock().unwrap();
1164-
let channel_state = channel_lock.borrow_parts();
1165-
let short_to_id = channel_state.short_to_id;
1166-
channel_state.by_id.retain(|_, v| {
1167-
if v.block_disconnected(header) {
1168-
let tx = v.force_shutdown();
1169-
for broadcast_tx in tx {
1170-
self.tx_broadcaster.broadcast_transaction(&broadcast_tx);
1171-
}
1172-
if let Some(short_id) = v.get_short_channel_id() {
1173-
short_to_id.remove(&short_id);
1215+
let mut new_events = Vec::new();
1216+
let mut failed_channels = Vec::new();
1217+
{
1218+
let mut channel_lock = self.channel_state.lock().unwrap();
1219+
let channel_state = channel_lock.borrow_parts();
1220+
let short_to_id = channel_state.short_to_id;
1221+
channel_state.by_id.retain(|_, v| {
1222+
if v.block_disconnected(header) {
1223+
if let Some(short_id) = v.get_short_channel_id() {
1224+
short_to_id.remove(&short_id);
1225+
}
1226+
failed_channels.push(v.force_shutdown());
1227+
if let Ok(update) = self.get_channel_update(&v) {
1228+
new_events.push(events::Event::BroadcastChannelUpdate {
1229+
msg: update
1230+
});
1231+
}
1232+
false
1233+
} else {
1234+
true
11741235
}
1175-
false
1176-
} else {
1177-
true
1236+
});
1237+
}
1238+
for failure in failed_channels.drain(..) {
1239+
self.finish_force_close_channel(failure);
1240+
}
1241+
if !new_events.is_empty() {
1242+
let mut pending_events = self.pending_events.lock().unwrap();
1243+
for funding_locked in new_events.drain(..) {
1244+
pending_events.push(funding_locked);
11781245
}
1179-
});
1246+
}
11801247
self.latest_block_height.fetch_sub(1, Ordering::AcqRel);
11811248
}
11821249
}
@@ -1855,6 +1922,7 @@ impl ChannelMessageHandler for ChannelManager {
18551922

18561923
fn peer_disconnected(&self, their_node_id: &PublicKey, no_connection_possible: bool) {
18571924
let mut new_events = Vec::new();
1925+
let mut failed_channels = Vec::new();
18581926
{
18591927
let mut channel_state_lock = self.channel_state.lock().unwrap();
18601928
let channel_state = channel_state_lock.borrow_parts();
@@ -1865,10 +1933,7 @@ impl ChannelMessageHandler for ChannelManager {
18651933
if let Some(short_id) = chan.get_short_channel_id() {
18661934
short_to_id.remove(&short_id);
18671935
}
1868-
let txn_to_broadcast = chan.force_shutdown();
1869-
for tx in txn_to_broadcast {
1870-
self.tx_broadcaster.broadcast_transaction(&tx);
1871-
}
1936+
failed_channels.push(chan.force_shutdown());
18721937
if let Ok(update) = self.get_channel_update(&chan) {
18731938
new_events.push(events::Event::BroadcastChannelUpdate {
18741939
msg: update
@@ -1889,6 +1954,9 @@ impl ChannelMessageHandler for ChannelManager {
18891954
}
18901955
}
18911956
}
1957+
for failure in failed_channels.drain(..) {
1958+
self.finish_force_close_channel(failure);
1959+
}
18921960
if !new_events.is_empty() {
18931961
let mut pending_events = self.pending_events.lock().unwrap();
18941962
for event in new_events.drain(..) {
@@ -2880,7 +2948,7 @@ mod tests {
28802948
let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
28812949
let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
28822950
nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2883-
assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
2951+
test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
28842952
}
28852953
get_announce_close_broadcast_events(&nodes, 0, 1);
28862954
assert_eq!(nodes[0].node.list_channels().len(), 0);
@@ -2895,7 +2963,7 @@ mod tests {
28952963
let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
28962964
let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
28972965
nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2898-
assert_eq!(nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
2966+
test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
28992967
}
29002968
get_announce_close_broadcast_events(&nodes, 1, 2);
29012969
assert_eq!(nodes[1].node.list_channels().len(), 0);
@@ -2990,14 +3058,15 @@ mod tests {
29903058
nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
29913059
{
29923060
let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2993-
assert_eq!(node_txn.len(), 1);
3061+
assert_eq!(node_txn.len(), 2);
29943062
assert_eq!(node_txn[0].input.len(), 1);
29953063

29963064
let mut funding_tx_map = HashMap::new();
29973065
funding_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
29983066
node_txn[0].verify(&funding_tx_map).unwrap();
2999-
node_txn.clear();
3067+
node_txn.swap_remove(0);
30003068
}
3069+
test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
30013070

30023071
nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
30033072
let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);

0 commit comments

Comments
 (0)