Skip to content

Commit fe1e9c4

Browse files
committed
More flexible fee rate estimates
1 parent 2c51080 commit fe1e9c4

File tree

8 files changed

+98
-82
lines changed

8 files changed

+98
-82
lines changed

fuzz/src/chanmon_consistency.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,10 @@ impl FeeEstimator for FuzzEstimator {
8080
// always return a HighPriority feerate here which is >= the maximum Normal feerate and a
8181
// Background feerate which is <= the minimum Normal feerate.
8282
match conf_target {
83-
ConfirmationTarget::HighPriority => MAX_FEE,
84-
ConfirmationTarget::Background|ConfirmationTarget::MempoolMinimum => 253,
85-
ConfirmationTarget::Normal => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE),
83+
ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee => MAX_FEE * 10,
84+
ConfirmationTarget::HtlcSweep => MAX_FEE,
85+
ConfirmationTarget::ChannelCloseMinimum|ConfirmationTarget::AnchorChannelFee|ConfirmationTarget::MinAllowedAnchorChannelRemoteFee|ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee => 253,
86+
ConfirmationTarget::NonAnchorChannelFee => cmp::min(self.ret_val.load(atomic::Ordering::Acquire), MAX_FEE),
8687
}
8788
}
8889
}

lightning/src/chain/chaininterface.rs

+44-16
Original file line numberDiff line numberDiff line change
@@ -48,21 +48,49 @@ pub trait BroadcasterInterface {
4848
/// estimation.
4949
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
5050
pub enum ConfirmationTarget {
51-
/// We'd like a transaction to confirm in the future, but don't want to commit most of the fees
52-
/// required to do so yet. The remaining fees will come via a Child-Pays-For-Parent (CPFP) fee
53-
/// bump of the transaction.
51+
/// We need to sweep an HTLC after a force close transaction. This should be a high priority
52+
/// transaction.
53+
HtlcSweep,
54+
/// The highest fee rate we will allow our channel counterparty to have in a non-anchor channel.
55+
/// Having this be a low value can cause force closures. Using 10x your [`HtlcSweep`] fee rate
56+
/// can be a good default.
5457
///
55-
/// The feerate returned should be the absolute minimum feerate required to enter most node
56-
/// mempools across the network. Note that if you are not able to obtain this feerate estimate,
57-
/// you should likely use the furthest-out estimate allowed by your fee estimator.
58-
MempoolMinimum,
59-
/// We are happy with a transaction confirming slowly, at least within a day or so worth of
60-
/// blocks.
61-
Background,
62-
/// We'd like a transaction to confirm without major delayed, i.e., within the next 12-24 blocks.
63-
Normal,
64-
/// We'd like a transaction to confirm in the next few blocks.
65-
HighPriority,
58+
/// This maximum is needed to prevent our counterparty from creating a channel which we cannot
59+
/// afford to force close because our HTLC outputs would become dust.
60+
///
61+
/// [`HtlcSweep`]: ConfirmationTarget::HtlcSweep
62+
MaxAllowedNonAnchorChannelRemoteFee,
63+
/// This needs to be sufficient to get into the mempool/get confirmed when the channel needs to
64+
/// be force-closed. Setting too low may result in force-closures. Because this is for anchor
65+
/// channels, it can be a low value as we can always bump the fee rate later.
66+
///
67+
/// A good estimate is the expected mempool minimum at the time of force-closure.
68+
MinAllowedAnchorChannelRemoteFee,
69+
/// The lowest fee rate we will allow our channel counterparty to have in a non-anchor channel.
70+
/// This needs to be sufficient to get into the mempool/get confirmed when the channel needs to
71+
/// be force-closed. Setting too low may result in force-closures.
72+
///
73+
/// A good estimate is at least within a day (144) or so worth of blocks.
74+
MinAllowedNonAnchorChannelRemoteFee,
75+
/// Fee rate to use for anchor channels. This is safe to be the mempool minimum when the channel
76+
/// needs to be force-closed.
77+
///
78+
/// This is the feerate for the pre-signed transactions which we will broadcast in the event of
79+
/// a force-closure, and needs to be sufficient at that time.
80+
AnchorChannelFee,
81+
/// Fee rate to use for non-anchor channels. A good estimate is within the next 12-24 blocks.
82+
///
83+
/// This is the feerate for the pre-signed transactions which we will broadcast in the event of
84+
/// a force-closure, and needs to be sufficient at that time.
85+
NonAnchorChannelFee,
86+
/// When cooperative closing channel, the minimum fee rate we will accept. Recommended at least
87+
/// within a day or so worth of blocks.
88+
///
89+
/// This will also be used when initiating a cooperative close of a channel. When closing a channel
90+
/// you can override this fee by using [`ChannelManager::close_channel_with_feerate_and_script`].
91+
///
92+
/// [`ChannelManager::close_channel_with_feerate_and_script`]: crate::ln::channelmanager::ChannelManager::close_channel_with_feerate_and_script
93+
ChannelCloseMinimum,
6694
}
6795

6896
/// A trait which should be implemented to provide feerate information on a number of time
@@ -135,7 +163,7 @@ mod tests {
135163
let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
136164
let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
137165

138-
assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background), FEERATE_FLOOR_SATS_PER_KW);
166+
assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), FEERATE_FLOOR_SATS_PER_KW);
139167
}
140168

141169
#[test]
@@ -144,6 +172,6 @@ mod tests {
144172
let test_fee_estimator = &TestFeeEstimator { sat_per_kw };
145173
let fee_estimator = LowerBoundedFeeEstimator::new(test_fee_estimator);
146174

147-
assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background), sat_per_kw);
175+
assert_eq!(fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee), sat_per_kw);
148176
}
149177
}

lightning/src/chain/onchaintx.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -580,7 +580,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
580580
if cached_request.is_malleable() {
581581
if cached_request.requires_external_funding() {
582582
let target_feerate_sat_per_1000_weight = cached_request.compute_package_feerate(
583-
fee_estimator, ConfirmationTarget::HighPriority, force_feerate_bump
583+
fee_estimator, ConfirmationTarget::HtlcSweep, force_feerate_bump
584584
);
585585
if let Some(htlcs) = cached_request.construct_malleable_package_with_external_funding(self) {
586586
return Some((
@@ -631,7 +631,7 @@ impl<ChannelSigner: WriteableEcdsaChannelSigner> OnchainTxHandler<ChannelSigner>
631631
debug_assert_eq!(tx.txid(), self.holder_commitment.trust().txid(),
632632
"Holder commitment transaction mismatch");
633633

634-
let conf_target = ConfirmationTarget::HighPriority;
634+
let conf_target = ConfirmationTarget::HtlcSweep;
635635
let package_target_feerate_sat_per_1000_weight = cached_request
636636
.compute_package_feerate(fee_estimator, conf_target, force_feerate_bump);
637637
if let Some(input_amount_sat) = output.funding_amount {

lightning/src/chain/package.rs

+7-22
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ use crate::ln::PaymentPreimage;
2424
use crate::ln::chan_utils::{TxCreationKeys, HTLCOutputInCommitment};
2525
use crate::ln::chan_utils;
2626
use crate::ln::msgs::DecodeError;
27-
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT};
27+
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, MIN_RELAY_FEE_SAT_PER_1000_WEIGHT, compute_feerate_sat_per_1000_weight};
2828
use crate::sign::WriteableEcdsaChannelSigner;
2929
use crate::chain::onchaintx::{ExternalHTLCClaim, OnchainTxHandler};
3030
use crate::util::logger::Logger;
@@ -1111,30 +1111,15 @@ fn compute_fee_from_spent_amounts<F: Deref, L: Deref>(input_amounts: u64, predic
11111111
where F::Target: FeeEstimator,
11121112
L::Target: Logger,
11131113
{
1114-
let mut updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64;
1115-
let mut fee = updated_feerate * (predicted_weight as u64) / 1000;
1114+
let sweep_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::HtlcSweep);
1115+
let fee_rate = cmp::min(sweep_feerate, compute_feerate_sat_per_1000_weight(input_amounts / 2, predicted_weight as u64)) as u64;
1116+
let fee = fee_rate * (predicted_weight as u64) / 1000;
11161117
if input_amounts <= fee {
1117-
updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal) as u64;
1118-
fee = updated_feerate * (predicted_weight as u64) / 1000;
1119-
if input_amounts <= fee {
1120-
updated_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background) as u64;
1121-
fee = updated_feerate * (predicted_weight as u64) / 1000;
1122-
if input_amounts <= fee {
1123-
log_error!(logger, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
1118+
log_error!(logger, "Failed to generate an on-chain punishment tx as even low priority fee ({} sat) was more than the entire claim balance ({} sat)",
11241119
fee, input_amounts);
1125-
None
1126-
} else {
1127-
log_warn!(logger, "Used low priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
1128-
input_amounts);
1129-
Some((fee, updated_feerate))
1130-
}
1131-
} else {
1132-
log_warn!(logger, "Used medium priority fee for on-chain punishment tx as high priority fee was more than the entire claim balance ({} sat)",
1133-
input_amounts);
1134-
Some((fee, updated_feerate))
1135-
}
1120+
None
11361121
} else {
1137-
Some((fee, updated_feerate))
1122+
Some((fee, fee_rate))
11381123
}
11391124
}
11401125

lightning/src/ln/channel.rs

+12-14
Original file line numberDiff line numberDiff line change
@@ -1168,7 +1168,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
11681168
match self.config.options.max_dust_htlc_exposure {
11691169
MaxDustHTLCExposure::FeeRateMultiplier(multiplier) => {
11701170
let feerate_per_kw = fee_estimator.bounded_sat_per_1000_weight(
1171-
ConfirmationTarget::HighPriority);
1171+
ConfirmationTarget::HtlcSweep);
11721172
feerate_per_kw as u64 * multiplier
11731173
},
11741174
MaxDustHTLCExposure::FixedLimitMsat(limit) => limit,
@@ -2155,21 +2155,17 @@ impl<SP: Deref> Channel<SP> where
21552155
// apply to channels supporting anchor outputs since HTLC transactions are pre-signed with a
21562156
// zero fee, so their fee is no longer considered to determine dust limits.
21572157
if !channel_type.supports_anchors_zero_fee_htlc_tx() {
2158-
let upper_limit = cmp::max(250 * 25,
2159-
fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::HighPriority) as u64 * 10);
2158+
let upper_limit =
2159+
fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MaxAllowedNonAnchorChannelRemoteFee) as u64;
21602160
if feerate_per_kw as u64 > upper_limit {
21612161
return Err(ChannelError::Close(format!("Peer's feerate much too high. Actual: {}. Our expected upper limit: {}", feerate_per_kw, upper_limit)));
21622162
}
21632163
}
21642164

2165-
// We can afford to use a lower bound with anchors than previously since we can now bump
2166-
// fees when broadcasting our commitment. However, we must still make sure we meet the
2167-
// minimum mempool feerate, until package relay is deployed, such that we can ensure the
2168-
// commitment transaction propagates throughout node mempools on its own.
21692165
let lower_limit_conf_target = if channel_type.supports_anchors_zero_fee_htlc_tx() {
2170-
ConfirmationTarget::MempoolMinimum
2166+
ConfirmationTarget::MinAllowedAnchorChannelRemoteFee
21712167
} else {
2172-
ConfirmationTarget::Background
2168+
ConfirmationTarget::MinAllowedNonAnchorChannelRemoteFee
21732169
};
21742170
let lower_limit = fee_estimator.bounded_sat_per_1000_weight(lower_limit_conf_target);
21752171
// Some fee estimators round up to the next full sat/vbyte (ie 250 sats per kw), causing
@@ -4155,8 +4151,10 @@ impl<SP: Deref> Channel<SP> where
41554151
// Propose a range from our current Background feerate to our Normal feerate plus our
41564152
// force_close_avoidance_max_fee_satoshis.
41574153
// If we fail to come to consensus, we'll have to force-close.
4158-
let mut proposed_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Background);
4159-
let normal_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4154+
let mut proposed_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::ChannelCloseMinimum);
4155+
// Use NonAnchorChannelFee because this should be an estimate for a channel close
4156+
// that we don't expect to be need fee bumping
4157+
let normal_feerate = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
41604158
let mut proposed_max_feerate = if self.context.is_outbound() { normal_feerate } else { u32::max_value() };
41614159

41624160
// The spec requires that (when the channel does not have anchors) we only send absolute
@@ -5727,9 +5725,9 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
57275725
debug_assert!(channel_type.is_subset(&channelmanager::provided_channel_type_features(&config)));
57285726

57295727
let commitment_conf_target = if channel_type.supports_anchors_zero_fee_htlc_tx() {
5730-
ConfirmationTarget::MempoolMinimum
5728+
ConfirmationTarget::AnchorChannelFee
57315729
} else {
5732-
ConfirmationTarget::Normal
5730+
ConfirmationTarget::NonAnchorChannelFee
57335731
};
57345732
let commitment_feerate = fee_estimator.bounded_sat_per_1000_weight(commitment_conf_target);
57355733

@@ -6019,7 +6017,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
60196017
// whatever reason.
60206018
if self.context.channel_type.supports_anchors_zero_fee_htlc_tx() {
60216019
self.context.channel_type.clear_anchors_zero_fee_htlc_tx();
6022-
self.context.feerate_per_kw = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
6020+
self.context.feerate_per_kw = fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
60236021
assert!(!self.context.channel_transaction_parameters.channel_type_features.supports_anchors_nonzero_fee_htlc_tx());
60246022
} else if self.context.channel_type.supports_scid_privacy() {
60256023
self.context.channel_type.clear_scid_privacy();

lightning/src/ln/channelmanager.rs

+17-18
Original file line numberDiff line numberDiff line change
@@ -2640,11 +2640,11 @@ where
26402640
/// will be accepted on the given channel, and after additional timeout/the closing of all
26412641
/// pending HTLCs, the channel will be closed on chain.
26422642
///
2643-
/// * If we are the channel initiator, we will pay between our [`Background`] and
2644-
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2645-
/// estimate.
2643+
/// * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2644+
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2645+
/// fee estimate.
26462646
/// * If our counterparty is the channel initiator, we will require a channel closing
2647-
/// transaction feerate of at least our [`Background`] feerate or the feerate which
2647+
/// transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
26482648
/// would appear on a force-closure transaction, whichever is lower. We will allow our
26492649
/// counterparty to pay as much fee as they'd like, however.
26502650
///
@@ -2656,8 +2656,8 @@ where
26562656
/// channel.
26572657
///
26582658
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2659-
/// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2660-
/// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2659+
/// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2660+
/// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
26612661
/// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
26622662
pub fn close_channel(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey) -> Result<(), APIError> {
26632663
self.close_channel_internal(channel_id, counterparty_node_id, None, None)
@@ -2671,8 +2671,8 @@ where
26712671
/// the channel being closed or not:
26722672
/// * If we are the channel initiator, we will pay at least this feerate on the closing
26732673
/// transaction. The upper-bound is set by
2674-
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`Normal`] fee
2675-
/// estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2674+
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2675+
/// fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
26762676
/// * If our counterparty is the channel initiator, we will refuse to accept a channel closure
26772677
/// transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
26782678
/// will appear on a force-closure transaction, whichever is lower).
@@ -2690,8 +2690,7 @@ where
26902690
/// channel.
26912691
///
26922692
/// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2693-
/// [`Background`]: crate::chain::chaininterface::ConfirmationTarget::Background
2694-
/// [`Normal`]: crate::chain::chaininterface::ConfirmationTarget::Normal
2693+
/// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
26952694
/// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
26962695
pub fn close_channel_with_feerate_and_script(&self, channel_id: &ChannelId, counterparty_node_id: &PublicKey, target_feerate_sats_per_1000_weight: Option<u32>, shutdown_script: Option<ShutdownScript>) -> Result<(), APIError> {
26972696
self.close_channel_internal(channel_id, counterparty_node_id, target_feerate_sats_per_1000_weight, shutdown_script)
@@ -4754,8 +4753,8 @@ where
47544753
PersistenceNotifierGuard::optionally_notify(self, || {
47554754
let mut should_persist = NotifyOption::SkipPersistNoEvents;
47564755

4757-
let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4758-
let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4756+
let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4757+
let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
47594758

47604759
let per_peer_state = self.per_peer_state.read().unwrap();
47614760
for (_cp_id, peer_state_mutex) in per_peer_state.iter() {
@@ -4765,9 +4764,9 @@ where
47654764
|(chan_id, phase)| if let ChannelPhase::Funded(chan) = phase { Some((chan_id, chan)) } else { None }
47664765
) {
47674766
let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4768-
min_mempool_feerate
4767+
anchor_feerate
47694768
} else {
4770-
normal_feerate
4769+
non_anchor_feerate
47714770
};
47724771
let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
47734772
if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }
@@ -4799,8 +4798,8 @@ where
47994798
PersistenceNotifierGuard::optionally_notify(self, || {
48004799
let mut should_persist = NotifyOption::SkipPersistNoEvents;
48014800

4802-
let normal_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::Normal);
4803-
let min_mempool_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::MempoolMinimum);
4801+
let non_anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::NonAnchorChannelFee);
4802+
let anchor_feerate = self.fee_estimator.bounded_sat_per_1000_weight(ConfirmationTarget::AnchorChannelFee);
48044803

48054804
let mut handle_errors: Vec<(Result<(), _>, _)> = Vec::new();
48064805
let mut timed_out_mpp_htlcs = Vec::new();
@@ -4847,9 +4846,9 @@ where
48474846
match phase {
48484847
ChannelPhase::Funded(chan) => {
48494848
let new_feerate = if chan.context.get_channel_type().supports_anchors_zero_fee_htlc_tx() {
4850-
min_mempool_feerate
4849+
anchor_feerate
48514850
} else {
4852-
normal_feerate
4851+
non_anchor_feerate
48534852
};
48544853
let chan_needs_persist = self.update_channel_fee(chan_id, chan, new_feerate);
48554854
if chan_needs_persist == NotifyOption::DoPersist { should_persist = NotifyOption::DoPersist; }

0 commit comments

Comments
 (0)