Skip to content

Commit e01b7b3

Browse files
Tell ChannelMonitors about HTLCs fulfilled after channel close
If a channel is about to hit the chain right as we receive a preimage, prior to this commit the relevant ChannelMonitor would never learn of this preimage.
1 parent 8a79877 commit e01b7b3

File tree

3 files changed

+60
-16
lines changed

3 files changed

+60
-16
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ use bitcoin::secp256k1;
4040
use ln::msgs::DecodeError;
4141
use ln::chan_utils;
4242
use ln::chan_utils::{CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HolderCommitmentTransaction, HTLCType};
43-
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash};
43+
use ln::channelmanager::{HTLCSource, PaymentPreimage, PaymentHash, MonitorUpdateInfo};
4444
use ln::onchaintx::{OnchainTxHandler, InputDescriptors};
4545
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
4646
use chain::transaction::{OutPoint, TransactionData};
@@ -182,9 +182,10 @@ pub enum MonitorEvent {
182182
pub struct HTLCUpdate {
183183
pub(crate) payment_hash: PaymentHash,
184184
pub(crate) payment_preimage: Option<PaymentPreimage>,
185-
pub(crate) source: HTLCSource
185+
pub(crate) source: HTLCSource,
186+
pub(crate) monitor_info: MonitorUpdateInfo
186187
}
187-
impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source });
188+
impl_writeable!(HTLCUpdate, 0, { payment_hash, payment_preimage, source, monitor_info });
188189

189190
/// If an HTLC expires within this many blocks, don't try to claim it in a shared transaction,
190191
/// instead claiming it in its own individual transaction.
@@ -1747,10 +1748,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
17471748
match ev {
17481749
OnchainEvent::HTLCUpdate { htlc_update } => {
17491750
log_trace!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
1751+
let latest_monitor_update_id = self.get_latest_update_id();
17501752
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
17511753
payment_hash: htlc_update.1,
17521754
payment_preimage: None,
17531755
source: htlc_update.0,
1756+
monitor_info: MonitorUpdateInfo {
1757+
funding_outpoint: self.funding_info.0,
1758+
latest_monitor_update_id
1759+
}
17541760
}));
17551761
},
17561762
OnchainEvent::MaturingOutput { descriptor } => {
@@ -2016,10 +2022,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
20162022
if !self.pending_monitor_events.iter().any(
20172023
|update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
20182024
payment_preimage.0.copy_from_slice(&input.witness[3]);
2025+
let latest_monitor_update_id = self.get_latest_update_id();
20192026
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
20202027
source,
20212028
payment_preimage: Some(payment_preimage),
2022-
payment_hash
2029+
payment_hash,
2030+
monitor_info: MonitorUpdateInfo {
2031+
funding_outpoint: self.funding_info.0,
2032+
latest_monitor_update_id
2033+
}
20232034
}));
20242035
}
20252036
} else if offered_preimage_claim {
@@ -2028,10 +2039,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
20282039
upd.source == source
20292040
} else { false }) {
20302041
payment_preimage.0.copy_from_slice(&input.witness[1]);
2042+
let latest_monitor_update_id = self.get_latest_update_id();
20312043
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
20322044
source,
20332045
payment_preimage: Some(payment_preimage),
2034-
payment_hash
2046+
payment_hash,
2047+
monitor_info: MonitorUpdateInfo {
2048+
funding_outpoint: self.funding_info.0,
2049+
latest_monitor_update_id
2050+
}
20352051
}));
20362052
}
20372053
} else {

lightning/src/ln/channel.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use bitcoin::secp256k1;
2525
use ln::features::{ChannelFeatures, InitFeatures};
2626
use ln::msgs;
2727
use ln::msgs::{DecodeError, OptionalField, DataLossProtect};
28-
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT};
28+
use ln::channelmanager::{PendingHTLCStatus, HTLCSource, HTLCFailReason, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT, MAX_LOCAL_BREAKDOWN_TIMEOUT, MonitorUpdateInfo};
2929
use ln::chan_utils::{CounterpartyCommitmentSecrets, HolderCommitmentTransaction, TxCreationKeys, HTLCOutputInCommitment, HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, make_funding_redeemscript, ChannelPublicKeys, PreCalculatedTxCreationKeys};
3030
use ln::chan_utils;
3131
use chain::chaininterface::{FeeEstimator,ConfirmationTarget};
@@ -1937,7 +1937,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
19371937
Err(ChannelError::Close("Remote tried to fulfill/fail an HTLC we couldn't find".to_owned()))
19381938
}
19391939

1940-
pub fn update_fulfill_htlc(&mut self, msg: &msgs::UpdateFulfillHTLC) -> Result<HTLCSource, ChannelError> {
1940+
pub fn update_fulfill_htlc(&mut self, msg: &msgs::UpdateFulfillHTLC) -> Result<(HTLCSource, MonitorUpdateInfo), ChannelError> {
19411941
if (self.channel_state & (ChannelState::ChannelFunded as u32)) != (ChannelState::ChannelFunded as u32) {
19421942
return Err(ChannelError::Close("Got fulfill HTLC message when channel was not in an operational state".to_owned()));
19431943
}
@@ -1946,7 +1946,16 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
19461946
}
19471947

19481948
let payment_hash = PaymentHash(Sha256::hash(&msg.payment_preimage.0[..]).into_inner());
1949-
self.mark_outbound_htlc_removed(msg.htlc_id, Some(payment_hash), None).map(|source| source.clone())
1949+
match self.mark_outbound_htlc_removed(msg.htlc_id, Some(payment_hash), None).map(|source| source.clone()) {
1950+
Ok(res) => {
1951+
let mon_info = MonitorUpdateInfo {
1952+
funding_outpoint: self.funding_txo.unwrap(),
1953+
latest_monitor_update_id: self.latest_monitor_update_id
1954+
};
1955+
Ok((res, mon_info))
1956+
},
1957+
Err(e) => Err(e)
1958+
}
19501959
}
19511960

19521961
pub fn update_fail_htlc(&mut self, msg: &msgs::UpdateFailHTLC, fail_reason: HTLCFailReason) -> Result<(), ChannelError> {

lightning/src/ln/channelmanager.rs

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use bitcoin::secp256k1;
3737
use chain;
3838
use chain::Watch;
3939
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
40-
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
40+
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
4141
use chain::transaction::{OutPoint, TransactionData};
4242
use ln::channel::{Channel, ChannelError};
4343
use ln::features::{InitFeatures, NodeFeatures};
@@ -698,6 +698,19 @@ macro_rules! maybe_break_monitor_err {
698698
}
699699
}
700700

701+
/// When claiming a payment after receiving a preimage, there's a rare case
702+
/// where the channel hits the chain before the `ChannelMonitor` can be updated
703+
/// with knowledge of the preimage. Thus, monitor information needs to be passed
704+
/// to the `ChannelManager` on receipt of a preimage so it's capable of updating
705+
/// the relevant `ChannelMonitor` after the channel's data has been removed from
706+
/// the `ChannelManager`'s `ChannelHolder`.
707+
#[derive(Clone, PartialEq)]
708+
pub(crate) struct MonitorUpdateInfo {
709+
pub(crate) funding_outpoint: OutPoint,
710+
pub(crate) latest_monitor_update_id: u64
711+
}
712+
impl_writeable!(MonitorUpdateInfo, 0, { funding_outpoint, latest_monitor_update_id });
713+
701714
impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<ChanSigner, M, T, K, F, L>
702715
where M::Target: chain::Watch<Keys=ChanSigner>,
703716
T::Target: BroadcasterInterface,
@@ -2125,7 +2138,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
21252138
} else { unreachable!(); }
21262139
}
21272140

2128-
fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage) {
2141+
fn claim_funds_internal(&self, mut channel_state_lock: MutexGuard<ChannelHolder<ChanSigner>>, source: HTLCSource, payment_preimage: PaymentPreimage, monitor_update_info: MonitorUpdateInfo) {
21292142
match source {
21302143
HTLCSource::OutboundRoute { .. } => {
21312144
mem::drop(channel_state_lock);
@@ -2138,9 +2151,15 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
21382151
if let Err((counterparty_node_id, err)) = match self.claim_funds_from_hop(&mut channel_state_lock, hop_data, payment_preimage) {
21392152
Ok(()) => Ok(()),
21402153
Err(None) => {
2141-
// TODO: There is probably a channel monitor somewhere that needs to
2142-
// learn the preimage as the channel already hit the chain and that's
2143-
// why it's missing.
2154+
let preimage_update = ChannelMonitorUpdate {
2155+
update_id: monitor_update_info.latest_monitor_update_id,
2156+
updates: vec![ChannelMonitorUpdateStep::PaymentPreimage {
2157+
payment_preimage: payment_preimage.clone(),
2158+
}],
2159+
};
2160+
if let Err(_) = self.chain_monitor.update_channel(monitor_update_info.funding_outpoint, preimage_update) {
2161+
// TODO(val): figure out what to do here
2162+
}
21442163
Ok(())
21452164
},
21462165
Err(Some(res)) => Err(res),
@@ -2582,7 +2601,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
25822601

25832602
fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
25842603
let mut channel_lock = self.channel_state.lock().unwrap();
2585-
let htlc_source = {
2604+
let (htlc_source, monitor_info) = {
25862605
let channel_state = &mut *channel_lock;
25872606
match channel_state.by_id.entry(msg.channel_id) {
25882607
hash_map::Entry::Occupied(mut chan) => {
@@ -2594,7 +2613,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
25942613
hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
25952614
}
25962615
};
2597-
self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2616+
self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone(), monitor_info);
25982617
Ok(())
25992618
}
26002619

@@ -2980,7 +2999,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
29802999
MonitorEvent::HTLCEvent(htlc_update) => {
29813000
if let Some(preimage) = htlc_update.payment_preimage {
29823001
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2983-
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3002+
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage, htlc_update.monitor_info);
29843003
} else {
29853004
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
29863005
self.fail_htlc_backwards_internal(self.channel_state.lock().unwrap(), htlc_update.source, &htlc_update.payment_hash, HTLCFailReason::Reason { failure_code: 0x4000 | 8, data: Vec::new() });

0 commit comments

Comments
 (0)