Skip to content

Commit df942d3

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 f35a5ce commit df942d3

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.
@@ -1741,10 +1742,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
17411742
match ev {
17421743
OnchainEvent::HTLCUpdate { htlc_update } => {
17431744
log_trace!(logger, "HTLC {} failure update has got enough confirmations to be passed upstream", log_bytes!((htlc_update.1).0));
1745+
let latest_monitor_update_id = self.get_latest_update_id();
17441746
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
17451747
payment_hash: htlc_update.1,
17461748
payment_preimage: None,
17471749
source: htlc_update.0,
1750+
monitor_info: MonitorUpdateInfo {
1751+
funding_outpoint: self.funding_info.0,
1752+
latest_monitor_update_id
1753+
}
17481754
}));
17491755
},
17501756
OnchainEvent::MaturingOutput { descriptor } => {
@@ -1985,10 +1991,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
19851991
if !self.pending_monitor_events.iter().any(
19861992
|update| if let &MonitorEvent::HTLCEvent(ref upd) = update { upd.source == source } else { false }) {
19871993
payment_preimage.0.copy_from_slice(&input.witness[3]);
1994+
let latest_monitor_update_id = self.get_latest_update_id();
19881995
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
19891996
source,
19901997
payment_preimage: Some(payment_preimage),
1991-
payment_hash
1998+
payment_hash,
1999+
monitor_info: MonitorUpdateInfo {
2000+
funding_outpoint: self.funding_info.0,
2001+
latest_monitor_update_id
2002+
}
19922003
}));
19932004
}
19942005
} else if offered_preimage_claim {
@@ -1997,10 +2008,15 @@ impl<ChanSigner: ChannelKeys> ChannelMonitor<ChanSigner> {
19972008
upd.source == source
19982009
} else { false }) {
19992010
payment_preimage.0.copy_from_slice(&input.witness[1]);
2011+
let latest_monitor_update_id = self.get_latest_update_id();
20002012
self.pending_monitor_events.push(MonitorEvent::HTLCEvent(HTLCUpdate {
20012013
source,
20022014
payment_preimage: Some(payment_preimage),
2003-
payment_hash
2015+
payment_hash,
2016+
monitor_info: MonitorUpdateInfo {
2017+
funding_outpoint: self.funding_info.0,
2018+
latest_monitor_update_id
2019+
}
20042020
}));
20052021
}
20062022
} 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
@@ -36,7 +36,7 @@ use bitcoin::secp256k1;
3636
use chain;
3737
use chain::Watch;
3838
use chain::chaininterface::{BroadcasterInterface, FeeEstimator};
39-
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
39+
use chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, ChannelMonitorUpdateErr, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent};
4040
use chain::transaction::{OutPoint, TransactionData};
4141
use ln::channel::{Channel, ChannelError};
4242
use ln::features::{InitFeatures, NodeFeatures};
@@ -697,6 +697,19 @@ macro_rules! maybe_break_monitor_err {
697697
}
698698
}
699699

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

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

25822601
fn internal_update_fulfill_htlc(&self, counterparty_node_id: &PublicKey, msg: &msgs::UpdateFulfillHTLC) -> Result<(), MsgHandleErrInternal> {
25832602
let mut channel_lock = self.channel_state.lock().unwrap();
2584-
let htlc_source = {
2603+
let (htlc_source, monitor_info) = {
25852604
let channel_state = &mut *channel_lock;
25862605
match channel_state.by_id.entry(msg.channel_id) {
25872606
hash_map::Entry::Occupied(mut chan) => {
@@ -2593,7 +2612,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
25932612
hash_map::Entry::Vacant(_) => return Err(MsgHandleErrInternal::send_err_msg_no_close("Failed to find corresponding channel".to_owned(), msg.channel_id))
25942613
}
25952614
};
2596-
self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone());
2615+
self.claim_funds_internal(channel_lock, htlc_source, msg.payment_preimage.clone(), monitor_info);
25972616
Ok(())
25982617
}
25992618

@@ -2979,7 +2998,7 @@ impl<ChanSigner: ChannelKeys, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
29792998
MonitorEvent::HTLCEvent(htlc_update) => {
29802999
if let Some(preimage) = htlc_update.payment_preimage {
29813000
log_trace!(self.logger, "Claiming HTLC with preimage {} from our monitor", log_bytes!(preimage.0));
2982-
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage);
3001+
self.claim_funds_internal(self.channel_state.lock().unwrap(), htlc_update.source, preimage, htlc_update.monitor_info);
29833002
} else {
29843003
log_trace!(self.logger, "Failing HTLC with hash {} from our monitor", log_bytes!(htlc_update.payment_hash.0));
29853004
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)