Skip to content

Commit b04720a

Browse files
committed
Add method to note transaction unconfirmed/reorged-out
1 parent 9577928 commit b04720a

File tree

2 files changed

+109
-24
lines changed

2 files changed

+109
-24
lines changed

lightning/src/ln/channel.rs

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ pub(super) struct Channel<Signer: Sign> {
377377

378378
/// The hash of the block in which the funding transaction was included.
379379
funding_tx_confirmed_in: Option<BlockHash>,
380-
funding_tx_confirmation_height: u64,
380+
funding_tx_confirmation_height: u32,
381381
short_channel_id: Option<u64>,
382382

383383
counterparty_dust_limit_satoshis: u64,
@@ -3591,7 +3591,7 @@ impl<Signer: Sign> Channel<Signer> {
35913591
}
35923592
}
35933593
}
3594-
self.funding_tx_confirmation_height = height as u64;
3594+
self.funding_tx_confirmation_height = height;
35953595
self.funding_tx_confirmed_in = Some(*block_hash);
35963596
self.short_channel_id = match scid_from_parts(height as u64, index_in_block as u64, txo_idx as u64) {
35973597
Ok(scid) => Some(scid),
@@ -3678,6 +3678,32 @@ impl<Signer: Sign> Channel<Signer> {
36783678
Ok((None, timed_out_htlcs))
36793679
}
36803680

3681+
/// Indicates the funding transaction is no longer confirmed in the main chain. This may
3682+
/// force-close the channel, but may also indicate a harmless reorganization of a block or two
3683+
/// before the channel has reached funding_locked and we can just wait for more blocks.
3684+
pub fn funding_transaction_unconfirmed(&mut self) -> Result<(), msgs::ErrorMessage> {
3685+
if self.funding_tx_confirmation_height != 0 {
3686+
// We handle the funding disconnection by calling update_best_block with a height one
3687+
// below where our funding was connected, implying a reorg back to conf_height - 1.
3688+
let reorg_height = self.funding_tx_confirmation_height - 1;
3689+
// We use the time field to bump the current time we set on channel updates if its
3690+
// larger. If we don't know that time has moved forward, we can just set it to the last
3691+
// time we saw and it will be ignored.
3692+
let best_time = self.update_time_counter;
3693+
match self.update_best_block(reorg_height, best_time) {
3694+
Ok((funding_locked, timed_out_htlcs)) => {
3695+
assert!(funding_locked.is_none(), "We can't generate a funding with 0 confirmations?");
3696+
assert!(timed_out_htlcs.is_empty(), "We can't have accepted HTLCs with a timeout before our funding confirmation?");
3697+
Ok(())
3698+
},
3699+
Err(e) => Err(e)
3700+
}
3701+
} else {
3702+
// We never learned about the funding confirmation anyway, just ignore
3703+
Ok(())
3704+
}
3705+
}
3706+
36813707
// Methods to get unprompted messages to send to the remote end (or where we already returned
36823708
// something in the handler for the message that prompted this message):
36833709

lightning/src/ln/channelmanager.rs

Lines changed: 81 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use bitcoin::hashes::hmac::{Hmac, HmacEngine};
2828
use bitcoin::hashes::sha256::Hash as Sha256;
2929
use bitcoin::hashes::sha256d::Hash as Sha256dHash;
3030
use bitcoin::hashes::cmp::fixed_time_eq;
31-
use bitcoin::hash_types::BlockHash;
31+
use bitcoin::hash_types::{BlockHash, Txid};
3232

3333
use bitcoin::secp256k1::key::{SecretKey,PublicKey};
3434
use bitcoin::secp256k1::Secp256k1;
@@ -3353,7 +3353,7 @@ where
33533353
"Blocks must be disconnected in chain-order - the disconnected block must have the correct height");
33543354
*self.last_block_hash.write().unwrap() = header.prev_blockhash;
33553355

3356-
self.do_chain_event(new_height, |channel| channel.update_best_block(new_height, header.time));
3356+
self.do_chain_event(Some(new_height), |channel| channel.update_best_block(new_height, header.time));
33573357
}
33583358
}
33593359

@@ -3364,8 +3364,11 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
33643364
F::Target: FeeEstimator,
33653365
L::Target: Logger,
33663366
{
3367+
/// Calls a function which handles an on-chain event (blocks dis/connected, transactions
3368+
/// un/confirmed, etc) on each channel, handling any resulting errors or messages generated by
3369+
/// the function.
33673370
fn do_chain_event<FN: Fn(&mut Channel<Signer>) -> Result<(Option<msgs::FundingLocked>, Vec<(HTLCSource, PaymentHash)>), msgs::ErrorMessage>>
3368-
(&self, height: u32, f: FN) {
3371+
(&self, height_opt: Option<u32>, f: FN) {
33693372
// Note that we MUST NOT end up calling methods on self.chain_monitor here - we're called
33703373
// during initialization prior to the chain_monitor being fully configured in some cases.
33713374
// See the docs for `ChannelManagerReadArgs` for more.
@@ -3424,24 +3427,26 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
34243427
true
34253428
});
34263429

3427-
channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3428-
htlcs.retain(|htlc| {
3429-
// If height is approaching the number of blocks we think it takes us to get
3430-
// our commitment transaction confirmed before the HTLC expires, plus the
3431-
// number of blocks we generally consider it to take to do a commitment update,
3432-
// just give up on it and fail the HTLC.
3433-
if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3434-
let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3435-
htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3436-
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3437-
failure_code: 0x4000 | 15,
3438-
data: htlc_msat_height_data
3439-
}));
3440-
false
3441-
} else { true }
3430+
if let Some(height) = height_opt {
3431+
channel_state.claimable_htlcs.retain(|&(ref payment_hash, _), htlcs| {
3432+
htlcs.retain(|htlc| {
3433+
// If height is approaching the number of blocks we think it takes us to get
3434+
// our commitment transaction confirmed before the HTLC expires, plus the
3435+
// number of blocks we generally consider it to take to do a commitment update,
3436+
// just give up on it and fail the HTLC.
3437+
if height >= htlc.cltv_expiry - HTLC_FAIL_BACK_BUFFER {
3438+
let mut htlc_msat_height_data = byte_utils::be64_to_array(htlc.value).to_vec();
3439+
htlc_msat_height_data.extend_from_slice(&byte_utils::be32_to_array(height));
3440+
timed_out_htlcs.push((HTLCSource::PreviousHopData(htlc.prev_hop.clone()), payment_hash.clone(), HTLCFailReason::Reason {
3441+
failure_code: 0x4000 | 15,
3442+
data: htlc_msat_height_data
3443+
}));
3444+
false
3445+
} else { true }
3446+
});
3447+
!htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
34423448
});
3443-
!htlcs.is_empty() // Only retain this entry if htlcs has at least one entry.
3444-
});
3449+
}
34453450
}
34463451

34473452
self.handle_init_event_channel_failures(failed_channels);
@@ -3477,7 +3482,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
34773482
log_trace!(self.logger, "{} transactions included in block {} at height {} provided", txdata.len(), block_hash, height);
34783483

34793484
let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3480-
self.do_chain_event(height, |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|a| (a, Vec::new())));
3485+
self.do_chain_event(Some(height), |channel| channel.transactions_confirmed(&block_hash, height, txdata, &self.logger).map(|a| (a, Vec::new())));
34813486
}
34823487

34833488
/// Updates channel state with the current best blockchain tip. You should attempt to call this
@@ -3506,7 +3511,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
35063511
self.latest_block_height.store(height as usize, Ordering::Release);
35073512
*self.last_block_hash.write().unwrap() = block_hash;
35083513

3509-
self.do_chain_event(height, |channel| channel.update_best_block(height, header.time));
3514+
self.do_chain_event(Some(height), |channel| channel.update_best_block(height, header.time));
35103515

35113516
loop {
35123517
// Update last_node_announcement_serial to be the max of its current value and the
@@ -3522,6 +3527,60 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelMana
35223527
}
35233528
}
35243529

3530+
/// Gets the set of txids which should be monitored for their confirmation state.
3531+
///
3532+
/// If you're providing information about reorganizations via [`transaction_unconfirmed`], this
3533+
/// is the set of transactions which you may need to call [`transaction_unconfirmed`] for.
3534+
///
3535+
/// This may be useful to poll to determine the set of transactions which must be registered
3536+
/// with an Electrum server or for which an Electrum server needs to be polled to determine
3537+
/// transaction confirmation state.
3538+
///
3539+
/// This may update after any [`transactions_confirmed`] or [`block_connected`] call.
3540+
///
3541+
/// Note that this is NOT the set of transactions which must be included in calls to
3542+
/// [`transactions_confirmed`] if they are confirmed, but a small subset of it.
3543+
///
3544+
/// [`transactions_confirmed`]: Self::transactions_confirmed
3545+
/// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
3546+
pub fn get_relevant_txids(&self) -> Vec<Txid> {
3547+
let channel_state = self.channel_state.lock().unwrap();
3548+
let mut res = Vec::with_capacity(channel_state.short_to_id.len());
3549+
for chan in channel_state.by_id.values() {
3550+
if let Some(funding_txo) = chan.get_funding_txo() {
3551+
res.push(funding_txo.txid);
3552+
}
3553+
}
3554+
res
3555+
}
3556+
3557+
/// Marks a transaction as having been reorganized out of the blockchain.
3558+
///
3559+
/// If a transaction is included in [`get_relevant_txids`], and is no longer in the main branch
3560+
/// of the blockchain, this function should be called to indicate that the transaction should
3561+
/// be considered reorganized out.
3562+
///
3563+
/// Once this is called, the given transaction will no longer appear on [`get_relevant_txids`],
3564+
/// though this may be called repeatedly for a given transaction without issue.
3565+
///
3566+
/// Note that if the transaction is confirmed on the main chain in a different block (indicated
3567+
/// via a call to [`transactions_confirmed`]), it may re-appear in [`get_relevant_txids`], thus
3568+
/// be very wary of race-conditions wherein the final state of a transaction indicated via
3569+
/// these APIs is not the same as its state on the blockchain.
3570+
///
3571+
/// [`transactions_confirmed`]: Self::transactions_confirmed
3572+
/// [`get_relevant_txids`]: Self::get_relevant_txids
3573+
pub fn transaction_unconfirmed(&self, txid: &Txid) {
3574+
let _persistence_guard = PersistenceNotifierGuard::new(&self.total_consistency_lock, &self.persistence_notifier);
3575+
self.do_chain_event(None, |channel| {
3576+
if let Some(funding_txo) = channel.get_funding_txo() {
3577+
if funding_txo.txid == *txid {
3578+
channel.funding_transaction_unconfirmed().map(|_| (None, Vec::new()))
3579+
} else { Ok((None, Vec::new())) }
3580+
} else { Ok((None, Vec::new())) }
3581+
});
3582+
}
3583+
35253584
/// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
35263585
/// indicating whether persistence is necessary. Only one listener on
35273586
/// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken

0 commit comments

Comments
 (0)