Skip to content

Commit e571c7a

Browse files
authored
Merge pull request #96 from TheBlueMatt/2018-07-force-close-handling
Add pending-HTLC-failure to and unify force_shutdown() handling
2 parents 982317a + c7c8a12 commit e571c7a

File tree

2 files changed

+210
-83
lines changed

2 files changed

+210
-83
lines changed

src/ln/channel.rs

Lines changed: 80 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ use chain::transaction::OutPoint;
2424
use util::{transaction_utils,rng};
2525
use util::sha2::Sha256;
2626

27+
use std;
2728
use std::default::Default;
2829
use std::{cmp,mem};
2930
use std::time::Instant;
@@ -927,7 +928,7 @@ impl Channel {
927928
Ok(our_sig)
928929
}
929930

930-
pub fn get_update_fulfill_htlc(&mut self, payment_preimage_arg: [u8; 32]) -> Result<Option<(msgs::UpdateFulfillHTLC, ChannelMonitor)>, HandleError> {
931+
fn get_update_fulfill_htlc(&mut self, payment_preimage_arg: [u8; 32]) -> Result<(Option<msgs::UpdateFulfillHTLC>, Option<ChannelMonitor>), HandleError> {
931932
// Either ChannelFunded got set (which means it wont bet unset) or there is no way any
932933
// caller thought we could have something claimed (cause we wouldn't have accepted in an
933934
// incoming HTLC anyway). If we got to ShutdownComplete, callers aren't allowed to call us,
@@ -942,13 +943,31 @@ impl Channel {
942943
let mut payment_hash_calc = [0; 32];
943944
sha.result(&mut payment_hash_calc);
944945

946+
let mut pending_idx = std::usize::MAX;
947+
for (idx, htlc) in self.pending_htlcs.iter().enumerate() {
948+
if !htlc.outbound && htlc.payment_hash == payment_hash_calc {
949+
if pending_idx != std::usize::MAX {
950+
panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!");
951+
}
952+
pending_idx = idx;
953+
}
954+
}
955+
if pending_idx == std::usize::MAX {
956+
return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None});
957+
}
958+
945959
// Now update local state:
960+
//
961+
// We have to put the payment_preimage in the channel_monitor right away here to ensure we
962+
// can claim it even if the channel hits the chain before we see their next commitment.
963+
self.channel_monitor.provide_payment_preimage(&payment_hash_calc, &payment_preimage_arg);
964+
946965
if (self.channel_state & (ChannelState::AwaitingRemoteRevoke as u32)) == (ChannelState::AwaitingRemoteRevoke as u32) {
947966
for pending_update in self.holding_cell_htlc_updates.iter() {
948967
match pending_update {
949968
&HTLCUpdateAwaitingACK::ClaimHTLC { ref payment_preimage, .. } => {
950969
if payment_preimage_arg == *payment_preimage {
951-
return Ok(None);
970+
return Ok((None, None));
952971
}
953972
},
954973
&HTLCUpdateAwaitingACK::FailHTLC { ref payment_hash, .. } => {
@@ -962,49 +981,39 @@ impl Channel {
962981
self.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::ClaimHTLC {
963982
payment_preimage: payment_preimage_arg, payment_hash: payment_hash_calc,
964983
});
965-
return Ok(None);
966-
}
967-
968-
let mut htlc_id = 0;
969-
let mut htlc_amount_msat = 0;
970-
for htlc in self.pending_htlcs.iter_mut() {
971-
if !htlc.outbound && htlc.payment_hash == payment_hash_calc {
972-
if htlc_id != 0 {
973-
panic!("Duplicate HTLC payment_hash, you probably re-used payment preimages, NEVER DO THIS!");
974-
}
975-
htlc_id = htlc.htlc_id;
976-
htlc_amount_msat += htlc.amount_msat;
977-
if htlc.state == HTLCState::Committed {
978-
htlc.state = HTLCState::LocalRemoved;
979-
htlc.local_removed_fulfilled = true;
980-
} else if htlc.state == HTLCState::RemoteAnnounced {
981-
panic!("Somehow forwarded HTLC prior to remote revocation!");
982-
} else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment {
983-
return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None});
984-
} else {
985-
panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state");
986-
}
984+
return Ok((None, Some(self.channel_monitor.clone())));
985+
}
986+
987+
let htlc_id = {
988+
let mut htlc = &mut self.pending_htlcs[pending_idx];
989+
if htlc.state == HTLCState::Committed {
990+
htlc.state = HTLCState::LocalRemoved;
991+
htlc.local_removed_fulfilled = true;
992+
} else if htlc.state == HTLCState::RemoteAnnounced {
993+
panic!("Somehow forwarded HTLC prior to remote revocation!");
994+
} else if htlc.state == HTLCState::LocalRemoved || htlc.state == HTLCState::LocalRemovedAwaitingCommitment {
995+
return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None});
996+
} else {
997+
panic!("Have an inbound HTLC when not awaiting remote revoke that had a garbage state");
987998
}
988-
}
989-
if htlc_amount_msat == 0 {
990-
return Err(HandleError{err: "Unable to find a pending HTLC which matched the given payment preimage", action: None});
991-
}
992-
self.channel_monitor.provide_payment_preimage(&payment_hash_calc, &payment_preimage_arg);
999+
htlc.htlc_id
1000+
};
9931001

994-
Ok(Some((msgs::UpdateFulfillHTLC {
1002+
Ok((Some(msgs::UpdateFulfillHTLC {
9951003
channel_id: self.channel_id(),
9961004
htlc_id: htlc_id,
9971005
payment_preimage: payment_preimage_arg,
998-
}, self.channel_monitor.clone())))
1006+
}), Some(self.channel_monitor.clone())))
9991007
}
10001008

1001-
pub fn get_update_fulfill_htlc_and_commit(&mut self, payment_preimage: [u8; 32]) -> Result<Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned, ChannelMonitor)>, HandleError> {
1009+
pub fn get_update_fulfill_htlc_and_commit(&mut self, payment_preimage: [u8; 32]) -> Result<(Option<(msgs::UpdateFulfillHTLC, msgs::CommitmentSigned)>, Option<ChannelMonitor>), HandleError> {
10021010
match self.get_update_fulfill_htlc(payment_preimage)? {
1003-
Some(update_fulfill_htlc) => {
1011+
(Some(update_fulfill_htlc), _) => {
10041012
let (commitment, monitor_update) = self.send_commitment_no_status_check()?;
1005-
Ok(Some((update_fulfill_htlc.0, commitment, monitor_update)))
1013+
Ok((Some((update_fulfill_htlc, commitment)), Some(monitor_update)))
10061014
},
1007-
None => Ok(None)
1015+
(None, Some(channel_monitor)) => Ok((None, Some(channel_monitor))),
1016+
(None, None) => Ok((None, None))
10081017
}
10091018
}
10101019

@@ -1491,7 +1500,7 @@ impl Channel {
14911500
},
14921501
&HTLCUpdateAwaitingACK::ClaimHTLC { payment_preimage, .. } => {
14931502
match self.get_update_fulfill_htlc(payment_preimage) {
1494-
Ok(update_fulfill_msg_option) => update_fulfill_htlcs.push(update_fulfill_msg_option.unwrap().0),
1503+
Ok(update_fulfill_msg_option) => update_fulfill_htlcs.push(update_fulfill_msg_option.0.unwrap()),
14951504
Err(e) => {
14961505
err = Some(e);
14971506
}
@@ -1827,6 +1836,7 @@ impl Channel {
18271836

18281837
/// Guaranteed to be Some after both FundingLocked messages have been exchanged (and, thus,
18291838
/// is_usable() returns true).
1839+
/// Allowed in any state (including after shutdown)
18301840
pub fn get_short_channel_id(&self) -> Option<u64> {
18311841
self.short_channel_id
18321842
}
@@ -1837,10 +1847,12 @@ impl Channel {
18371847
self.channel_monitor.get_funding_txo()
18381848
}
18391849

1850+
/// Allowed in any state (including after shutdown)
18401851
pub fn get_their_node_id(&self) -> PublicKey {
18411852
self.their_node_id
18421853
}
18431854

1855+
/// Allowed in any state (including after shutdown)
18441856
pub fn get_our_htlc_minimum_msat(&self) -> u64 {
18451857
self.our_htlc_minimum_msat
18461858
}
@@ -1849,6 +1861,7 @@ impl Channel {
18491861
self.channel_value_satoshis
18501862
}
18511863

1864+
/// Allowed in any state (including after shutdown)
18521865
pub fn get_channel_update_count(&self) -> u32 {
18531866
self.channel_update_count
18541867
}
@@ -1858,6 +1871,7 @@ impl Channel {
18581871
}
18591872

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

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

18851900
/// Returns true if this channel is currently available for use. This is a superset of
18861901
/// is_usable() and considers things like the channel being temporarily disabled.
1902+
/// Allowed in any state (including after shutdown)
18871903
pub fn is_live(&self) -> bool {
18881904
self.is_usable()
18891905
}
@@ -2323,14 +2339,39 @@ impl Channel {
23232339
}
23242340

23252341
/// Gets the latest commitment transaction and any dependant transactions for relay (forcing
2326-
/// shutdown of this channel - no more calls into this Channel may be made afterwards.
2327-
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]>) {
23282347
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+
23292370
self.channel_state = ChannelState::ShutdownComplete as u32;
23302371
self.channel_update_count += 1;
23312372
let mut res = Vec::new();
23322373
mem::swap(&mut res, &mut self.last_local_commitment_txn);
2333-
res
2374+
(res, dropped_outbound_htlcs)
23342375
}
23352376
}
23362377

0 commit comments

Comments
 (0)