Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lightning/src/chain/channelmonitor.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2426,7 +2426,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
}));
},
ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight, htlcs,
target_feerate_sat_per_1000_weight, htlcs, tx_lock_time,
} => {
let mut htlc_descriptors = Vec::with_capacity(htlcs.len());
for htlc in htlcs {
Expand All@@ -2444,6 +2444,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
ret.push(Event::BumpTransaction(BumpTransactionEvent::HTLCResolution {
target_feerate_sat_per_1000_weight,
htlc_descriptors,
tx_lock_time,
}));
}
}
Expand Down
17 changes: 12 additions & 5 deletions lightning/src/chain/onchaintx.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,6 +12,8 @@
//! OnchainTxHandler objects are fully-part of ChannelMonitor and encapsulates all
//! building, tracking, bumping and notifications functions.

#[cfg(anchors)]
use bitcoin::PackedLockTime;
use bitcoin::blockdata::transaction::Transaction;
use bitcoin::blockdata::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::blockdata::script::Script;
Expand DownExpand Up@@ -201,6 +203,7 @@ pub(crate) enum ClaimEvent {
BumpHTLC {
target_feerate_sat_per_1000_weight: u32,
htlcs: Vec<ExternalHTLCClaim>,
tx_lock_time: PackedLockTime,
},
}

Expand DownExpand Up@@ -544,6 +547,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
OnchainClaim::Event(ClaimEvent::BumpHTLC {
target_feerate_sat_per_1000_weight,
htlcs,
tx_lock_time: PackedLockTime(cached_request.package_locktime(cur_height)),
}),
));
} else {
Expand All@@ -558,7 +562,9 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
) {
assert!(new_feerate != 0);

let transaction = cached_request.finalize_malleable_package(self, output_value, self.destination_script.clone(), logger).unwrap();
let transaction = cached_request.finalize_malleable_package(
cur_height, self, output_value, self.destination_script.clone(), logger
).unwrap();
log_trace!(logger, "...with timer {} and feerate {}", new_timer.unwrap(), new_feerate);
assert!(predicted_weight >= transaction.weight());
return Some((new_timer, new_feerate, OnchainClaim::Tx(transaction)));
Expand DownExpand Up@@ -654,16 +660,17 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
.find(|locked_package| locked_package.outpoints() == req.outpoints());
if let Some(package) = timelocked_equivalent_package {
log_info!(logger, "Ignoring second claim for outpoint {}:{}, we already have one which we're waiting on a timelock at {} for.",
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_timelock());
req.outpoints()[0].txid, req.outpoints()[0].vout, package.package_locktime(cur_height));
continue;
}

if req.package_timelock() > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", req.package_timelock(), cur_height);
let package_locktime = req.package_locktime(cur_height);
if package_locktime > cur_height + 1 {
log_info!(logger, "Delaying claim of package until its timelock at {} (current height {}), the following outpoints are spent:", package_locktime, cur_height);
for outpoint in req.outpoints() {
log_info!(logger, " Outpoint {}", outpoint);
}
self.locktimed_packages.entry(req.package_timelock()).or_insert(Vec::new()).push(req);
self.locktimed_packages.entry(package_locktime).or_insert(Vec::new()).push(req);
continue;
}

Expand Down
66 changes: 49 additions & 17 deletions lightning/src/chain/package.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -434,7 +434,6 @@ impl PackageSolvingData {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, onchain_handler.opt_anchors(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);

bumped_tx.lock_time = PackedLockTime(outp.htlc.cltv_expiry); // Right now we don't aggregate time-locked transaction, if we do we should set lock_time before to avoid breaking hash computation
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
Expand All@@ -460,18 +459,23 @@ impl PackageSolvingData {
_ => { panic!("API Error!"); }
}
}
fn absolute_tx_timelock(&self, output_conf_height: u32) -> u32 {
// Get the absolute timelock at which this output can be spent given the height at which
// this output was confirmed. We use `output_conf_height + 1` as a safe default as we can
// be confirmed in the next block and transactions with time lock `current_height + 1`
// always propagate.
fn absolute_tx_timelock(&self, current_height: u32) -> u32 {
// We use `current_height + 1` as our default locktime to discourage fee sniping and because
// transactions with it always propagate.
let absolute_timelock = match self {
PackageSolvingData::RevokedOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => output_conf_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderHTLCOutput(ref outp) => cmp::max(outp.cltv_expiry, output_conf_height + 1),
PackageSolvingData::HolderFundingOutput(_) => output_conf_height + 1,
PackageSolvingData::RevokedOutput(_) => current_height + 1,
PackageSolvingData::RevokedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyOfferedHTLCOutput(_) => current_height + 1,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => cmp::max(outp.htlc.cltv_expiry, current_height + 1),
// HTLC timeout/success transactions rely on a fixed timelock due to the counterparty's
// signature.
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
outp.cltv_expiry
},
PackageSolvingData::HolderFundingOutput(_) => current_height + 1,
};
absolute_timelock
}
Expand DownExpand Up@@ -638,9 +642,36 @@ impl PackageTemplate {
}
amounts
}
pub(crate) fn package_timelock(&self) -> u32 {
self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(self.height_original))
.max().expect("There must always be at least one output to spend in a PackageTemplate")
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let locktime = self.inputs.iter().map(|(_, outp)| outp.absolute_tx_timelock(current_height))
.max().expect("There must always be at least one output to spend in a PackageTemplate");

// If we ever try to aggregate a `HolderHTLCOutput`s with another output type, we'll likely
// end up with an incorrect transaction locktime since the counterparty has included it in
// its HTLC signature. This should never happen unless we decide to aggregate outputs across
// different channel commitments.
#[cfg(debug_assertions)] {
if self.inputs.iter().any(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
outp.preimage.is_some()
} else {
false
}
) {
debug_assert_eq!(locktime, 0);
};
for timeout_htlc_expiry in self.inputs.iter().filter_map(|(_, outp)|
if let PackageSolvingData::HolderHTLCOutput(outp) = outp {
if outp.preimage.is_none() {
Some(outp.cltv_expiry)
} else { None }
} else { None }
) {
debug_assert_eq!(locktime, timeout_htlc_expiry);
}
}

locktime
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> usize {
let mut inputs_weight = 0;
Expand DownExpand Up@@ -676,12 +707,13 @@ impl PackageTemplate {
htlcs
}
pub(crate) fn finalize_malleable_package<L: Deref, Signer: WriteableEcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64, destination_script: Script, logger: &L
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: u64,
destination_script: Script, logger: &L
) -> Option<Transaction> where L::Target: Logger {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: 2,
lock_time: PackedLockTime::ZERO,
lock_time: PackedLockTime(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,
Expand Down
2 changes: 2 additions & 0 deletions lightning/src/events/bump_transaction.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -227,5 +227,7 @@ pub enum BumpTransactionEvent {
/// The set of pending HTLCs on the confirmed commitment that need to be claimed, preferably
/// by the same transaction.
htlc_descriptors: Vec<HTLCDescriptor>,
/// The locktime required for the resulting HTLC transaction.
tx_lock_time: PackedLockTime,
},
}
6 changes: 3 additions & 3 deletions lightning/src/ln/functional_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2843,7 +2843,7 @@ fn test_htlc_on_chain_success() {
assert_eq!(commitment_spend.input.len(), 2);
assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert_eq!(commitment_spend.lock_time.0, 0);
assert_eq!(commitment_spend.lock_time.0, nodes[1].best_block_info().1 + 1);
assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
// We don't bother to check that B can claim the HTLC output on its commitment tx here as
// we already checked the same situation with A.
Expand DownExpand Up@@ -4699,7 +4699,7 @@ fn test_onchain_to_onchain_claim() {
check_spends!(b_txn[0], commitment_tx[0]);
assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
assert_eq!(b_txn[0].lock_time.0, 0); // Success tx
assert_eq!(b_txn[0].lock_time.0, nodes[1].best_block_info().1 + 1); // Success tx

check_closed_broadcast!(nodes[1], true);
check_added_monitors!(nodes[1], 1);
Expand DownExpand Up@@ -6860,7 +6860,7 @@ fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
if !revoked {
assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
} else {
assert_eq!(timeout_tx[0].lock_time.0, 0);
assert_eq!(timeout_tx[0].lock_time.0, 12);
}
// We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
mine_transaction(&nodes[0], &timeout_tx[0]);
Expand Down
11 changes: 4 additions & 7 deletions lightning/src/ln/monitor_tests.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -1775,7 +1775,7 @@ fn test_yield_anchors_events() {
let mut htlc_txs = Vec::with_capacity(2);
for event in holder_events {
match event {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, .. }) => {
Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { htlc_descriptors, tx_lock_time, .. }) => {
assert_eq!(htlc_descriptors.len(), 1);
let htlc_descriptor = &htlc_descriptors[0];
let signer = nodes[0].keys_manager.derive_channel_keys(
Expand All@@ -1784,11 +1784,7 @@ fn test_yield_anchors_events() {
let per_commitment_point = signer.get_per_commitment_point(htlc_descriptor.per_commitment_number, &secp);
let mut htlc_tx = Transaction {
version: 2,
lock_time: if htlc_descriptor.htlc.offered {
PackedLockTime(htlc_descriptor.htlc.cltv_expiry)
} else {
PackedLockTime::ZERO
},
lock_time: tx_lock_time,
input: vec![
htlc_descriptor.unsigned_tx_input(), // HTLC input
TxIn { ..Default::default() } // Fee input
Expand DownExpand Up@@ -2064,7 +2060,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
};
let mut descriptors = Vec::with_capacity(4);
for event in events {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, .. }) = event {
if let Event::BumpTransaction(BumpTransactionEvent::HTLCResolution { mut htlc_descriptors, tx_lock_time, .. }) = event {
assert_eq!(htlc_descriptors.len(), 2);
for htlc_descriptor in &htlc_descriptors {
assert!(!htlc_descriptor.htlc.offered);
Expand All@@ -2076,6 +2072,7 @@ fn test_anchors_aggregated_revoked_htlc_tx() {
htlc_tx.output.push(htlc_descriptor.tx_output(&per_commitment_point, &secp));
}
descriptors.append(&mut htlc_descriptors);
htlc_tx.lock_time = tx_lock_time;
} else {
panic!("Unexpected event");
}
Expand Down